Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: parse sse #532

Merged
merged 2 commits into from
Oct 30, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 18 additions & 18 deletions src/utils/fetch-sse.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -13,29 +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'),
)
}
Comment on lines +16 to +31
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

这部分是不需要的, 原来的样子就行, 在fetchSSE具体使用中的回调函数内已经处理了

}
}
})
let hasStarted = false
for await (const chunk of streamAsyncIterable(resp.body)) {
const str = new TextDecoder().decode(chunk)
if (!str.startsWith('{') && !str.startsWith('"{')) {
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

这里是为了检测返回的不是json, 也就是检测是sse, 但这个检测方式确实不好, 已经修改

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)
Comment on lines -25 to -34
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

这部分代码实际上是为了使fetchsse也能用于fetch普通的http响应

} catch (error) {
console.debug('json error', error)
}
}
parser.feed(str)

if (!hasStarted) {
hasStarted = true
Expand Down