Created
March 1, 2018 18:48
-
-
Save harrishancock/4887347976924c80ec73e101aa884220 to your computer and use it in GitHub Desktop.
Cloudflare Workers streaming response bodies example with unconditional 200
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
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