Skip to content

Instantly share code, notes, and snippets.

@harrishancock
Created March 1, 2018 18:48
Show Gist options
  • Save harrishancock/4887347976924c80ec73e101aa884220 to your computer and use it in GitHub Desktop.
Save harrishancock/4887347976924c80ec73e101aa884220 to your computer and use it in GitHub Desktop.
Cloudflare Workers streaming response bodies example with unconditional 200
addEventListener('fetch', event => {
event.respondWith(fetchAndApply(event.request))
})
/**
* Make multiple requests,
* aggregate the responses and
* stream it back as a single response.
*/
async function fetchAndApply(request) {
const requestInit = {
headers: { "Authorization": "XXXXXX" }
}
const fetches = [
"https://api.coinbase.com/v2/prices/BTC-USD/spot",
"https://api.coinbase.com/v2/prices/ETH-USD/spot",
"https://api.coinbase.com/v2/prices/LTC-USD/spot"
].map(url => fetch(url, requestInit))
// Create a pipe and stream the response bodies out
// as a JSON array.
let { readable, writable } = new TransformStream()
streamJsonResponseBodies(fetches, writable)
return new Response(readable)
}
async function streamJsonResponseBodies(fetches, writable) {
let writer = writable.getWriter()
let encoder = new TextEncoder()
await writer.write(encoder.encode("[\n"))
for (let i = 0; i < fetches.length; ++i) {
let response = await fetches[i]
if (i > 0) await writer.write(encoder.encode(",\n"))
await manualPipeTo(response.body.getReader(), writer)
}
await writer.write(encoder.encode("]"))
await writer.close()
}
async function manualPipeTo(reader, writer) {
while (true) {
const { done, value } = await reader.read()
if (done) break
await writer.write(value)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment