Skip to content

Commit 0f3ec38

Browse files
bowencooljosStorer
authored andcommitted
re-order parse process
1 parent f2098d8 commit 0f3ec38

File tree

1 file changed

+18
-19
lines changed

1 file changed

+18
-19
lines changed

src/utils/fetch-sse.mjs

Lines changed: 18 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -13,30 +13,29 @@ export async function fetchSSE(resource, options) {
1313
}
1414
const parser = createParser((event) => {
1515
if (event.type === 'event') {
16-
onMessage(event.data)
16+
if (event.data === '[DONE]') {
17+
onMessage(event.data)
18+
} else {
19+
try {
20+
JSON.parse(event.data)
21+
onMessage(event.data)
22+
} catch (error) {
23+
console.error('json error', error)
24+
onMessage(
25+
event.data
26+
.replace(/^"|"$/g, '')
27+
.replaceAll('\\"', '"')
28+
.replaceAll('\\\\u', '\\u')
29+
.replaceAll('\\\\n', '\\n'),
30+
)
31+
}
32+
}
1733
}
1834
})
1935
let hasStarted = false
2036
for await (const chunk of streamAsyncIterable(resp.body)) {
2137
const str = new TextDecoder().decode(chunk)
22-
if (!str.startsWith('{') && !str.startsWith('"{')) {
23-
parser.feed(str)
24-
} else {
25-
try {
26-
const formattedData = JSON.parse(
27-
str
28-
.replace(/^"|"$/g, '')
29-
.replaceAll('\\"', '"')
30-
.replaceAll('\\\\u', '\\u')
31-
.replaceAll('\\\\n', '\\n'),
32-
)
33-
const formattedStr = 'data: ' + JSON.stringify(formattedData) + '\n\ndata: [DONE]\n\n'
34-
parser.feed(formattedStr)
35-
} catch (error) {
36-
console.debug('json error', error)
37-
parser.feed(str)
38-
}
39-
}
38+
parser.feed(str)
4039

4140
if (!hasStarted) {
4241
hasStarted = true

0 commit comments

Comments
 (0)