Skip to content

Instantly share code, notes, and snippets.

@blackbing
Last active May 7, 2024 22:07
Show Gist options
  • Save blackbing/22ed6db703727fb050a071ce2911684f to your computer and use it in GitHub Desktop.
Save blackbing/22ed6db703727fb050a071ce2911684f to your computer and use it in GitHub Desktop.
Server Sent Event with fetch stream
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);
}
})
@blackbing
Copy link
Author

blackbing commented Feb 1, 2023

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment