-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathparseJSONSSE.ts
More file actions
40 lines (34 loc) · 992 Bytes
/
parseJSONSSE.ts
File metadata and controls
40 lines (34 loc) · 992 Bytes
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
export const parseJsonSSE = async <T>({
data,
onParse,
onFinish
}: {
data: ReadableStream
onParse: (object: T) => void
onFinish: () => void
}) => {
const reader = data.getReader()
const decoder = new TextDecoder()
let done = false
let tempState = ""
while (!done) {
// eslint-disable-next-line no-await-in-loop
const { value, done: doneReading } = await reader.read()
done = doneReading
const newValue = decoder.decode(value).split("\n\n").filter(Boolean)
if (tempState) {
newValue[0] = tempState + newValue[0]
tempState = ""
}
// eslint-disable-next-line @typescript-eslint/no-loop-func
newValue.forEach((newVal) => {
try {
const json = JSON.parse(newVal.replace("data: ", "")) as T
onParse(json)
} catch (error) {
tempState = newVal
}
})
}
onFinish()
}