Skip to content

Instantly share code, notes, and snippets.

@HereOrCode
Forked from blackbing/fetchStream.js
Created January 17, 2024 00:56
Show Gist options
  • Save HereOrCode/db128f44e39630f75c4999f57595b402 to your computer and use it in GitHub Desktop.
Save HereOrCode/db128f44e39630f75c4999f57595b402 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);
}
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment