-
Notifications
You must be signed in to change notification settings - Fork 2
/
event.ts
37 lines (32 loc) · 915 Bytes
/
event.ts
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
import { FastifyError } from 'fastify'
import fastJson from 'fast-json-stringify'
const stringifyEventData = fastJson({
title: 'Stream Event Data',
type: 'object',
properties: {
// Success
response: { type: 'string' },
// Error
code: { type: 'string' },
message: { type: 'string' }
}
})
export interface AiStreamEventContent {
response: string
}
export type AiStreamEvent = {
event: 'content'
data: AiStreamEventContent
} | {
event: 'error'
data: FastifyError
}
/**
* Encode an event to the Event Stream format
* @see https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events#event_stream_format
*/
export function encodeEvent ({ event, data }: AiStreamEvent): Uint8Array {
const jsonString = stringifyEventData(data)
const eventString = `event: ${event}\ndata: ${jsonString}\n\n`
return new TextEncoder().encode(eventString)
}