const url = "https://backend.chatfly.co/api/chat/get-streaming-response";
const headers = {
"Content-Type": "application/json"
};
const data = {
bot_id: "xxxx-xxxx-xxxx-xxxx",
message: "string",
session_id: "xxxx-xxxx-xxxx-xxxx",
user_id: "xxxx-xxxx-xxxx-xxxx",
sender: "xxxx-xxxx-xxxx-xxxx"
};
const decoder = new TextDecoder('utf-8');
fetch(url, {
method: 'POST',
headers: headers,
body: JSON.stringify(data),
})
.then(response => {
// Check for error response
if (!response.ok) {
return response.text().then(errorText => {
throw new Error(`Request failed with status code:: ${response.status} - ${errorText}`);
});
}
console.log("Request successful!");
// Otherwise, return the streaming response body
return response.body;
})
.then(stream => {
// Create a reader to read the stream
const reader = stream.getReader();
// Define the function that will handle the stream
function read() {
reader.read().then(({ done, value }) => {
// Check to see if we're done with the stream
if (done) {
return;
}
// Convert the value (a Uint8Array) to a string
const text = decoder.decode(value);
process.stdout.write(text);
// Read some more, and call this function again
read();
});
}
// Start reading the stream
read();
})
.catch(error => {
console.error(`An error occurred: ${error}`);
});