-
-
Notifications
You must be signed in to change notification settings - Fork 12
/
use-api-server-streaming.js
53 lines (51 loc) · 1.55 KB
/
use-api-server-streaming.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
// Run the server first with `npm run server`
import { fetchEventSource } from '@waylaidwanderer/fetch-event-source';
const opts = {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
message: 'Hello',
// Set stream to true to receive each token as it is generated.
stream: true,
}),
};
try {
let reply = '';
const controller = new AbortController();
await fetchEventSource('http://localhost:3001/conversation', {
...opts,
signal: controller.signal,
onopen(response) {
if (response.status === 200) {
return;
}
throw new Error(`Failed to send message. HTTP ${response.status} - ${response.statusText}`);
},
onclose() {
throw new Error('Failed to send message. Server closed the connection unexpectedly.');
},
onerror(err) {
throw err;
},
onmessage(message) {
// { data: 'Hello', event: '', id: '', retry: undefined }
if (message.data === '[DONE]') {
controller.abort();
console.log(message);
return;
}
if (message.event === 'result') {
const result = JSON.parse(message.data);
console.log(result);
return;
}
console.log(message);
reply += JSON.parse(message.data);
},
});
console.log(reply);
} catch (err) {
console.log('ERROR', err);
}