Last active
September 1, 2024 08:05
-
-
Save blackbing/22ed6db703727fb050a071ce2911684f to your computer and use it in GitHub Desktop.
Server Sent Event with fetch stream
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const url = 'https://api.example.com/v1/sse'; | |
const accessToken = 'test'; | |
fetch(url, { | |
headers: { | |
Authorization: `Bearer ${accessToken}`, | |
}, | |
}) | |
.then(response => { | |
if (response.ok && response.body) { | |
reader = response.body.pipeThrough(new TextDecoderStream()).getReader(); | |
const readStream = () => | |
reader.read().then(({ | |
value, | |
done | |
}) => { | |
if (done) { | |
reader.cancel(); | |
return Promise.resolve(); | |
} | |
// parse the data | |
const data = /{.*}/.exec(value); | |
if (!data || !data[0]) { | |
return readStream(); | |
} | |
const res = JSON.parse(data[0]); | |
// do something if success | |
// and cancel the stream | |
// reader.cancel().catch(() => null); | |
return readStream(); | |
}); | |
return readStream(); | |
} else { | |
return Promise.reject(response); | |
} | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
original article: https://blackbing.medium.com/%E6%B7%BA%E8%AB%87-server-sent-events-9c81ef21ca8e