Skip to content

Commit

Permalink
re-order parse process
Browse files Browse the repository at this point in the history
  • Loading branch information
bowencool authored and josStorer committed Oct 30, 2023
1 parent f2098d8 commit 0f3ec38
Showing 1 changed file with 18 additions and 19 deletions.
37 changes: 18 additions & 19 deletions src/utils/fetch-sse.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -13,30 +13,29 @@ export async function fetchSSE(resource, options) {
}
const parser = createParser((event) => {
if (event.type === 'event') {
onMessage(event.data)
if (event.data === '[DONE]') {
onMessage(event.data)
} else {
try {
JSON.parse(event.data)
onMessage(event.data)
} catch (error) {
console.error('json error', error)
onMessage(
event.data
.replace(/^"|"$/g, '')
.replaceAll('\\"', '"')
.replaceAll('\\\\u', '\\u')
.replaceAll('\\\\n', '\\n'),
)
}
}
}
})
let hasStarted = false
for await (const chunk of streamAsyncIterable(resp.body)) {
const str = new TextDecoder().decode(chunk)
if (!str.startsWith('{') && !str.startsWith('"{')) {
parser.feed(str)
} else {
try {
const formattedData = JSON.parse(
str
.replace(/^"|"$/g, '')
.replaceAll('\\"', '"')
.replaceAll('\\\\u', '\\u')
.replaceAll('\\\\n', '\\n'),
)
const formattedStr = 'data: ' + JSON.stringify(formattedData) + '\n\ndata: [DONE]\n\n'
parser.feed(formattedStr)
} catch (error) {
console.debug('json error', error)
parser.feed(str)
}
}
parser.feed(str)

if (!hasStarted) {
hasStarted = true
Expand Down

0 comments on commit 0f3ec38

Please sign in to comment.