How to cache streams?
# workers-help
k
app.get("/download", async (ctx) => { const address = ctx.req.query("address"); try { if (address) { const url = new URL(decodeURIComponent(address)); url.protocol = "https"; const { readable, writable } = new TransformStream(); url.protocol = "https"; const result = await fetch(url, { headers: { ...ctx.req.headers, redirect: "follow", "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/112.0.0.0 Safari/537.36", }, }); let contentLength = result.headers.get("Content-Length"); let response = new Response(result.body); response.headers.append("Cache-Control", "no-cache"); response.headers.append("content-type", "audio/mpeg"); if (contentLength) { response.headers.append("Content-Length", contentLength); } response.body?.pipeTo(writable); return new Response(readable, response); } return ctx.newResponse("Not Found", 404); } catch (error) { console.log(error); return ctx.newResponse("Internal Server Error", 500); } }); I have this script that i can use to proxy a audio file from a url, how can i cache this audio file in cache? so i don't have to ping the server?
k
Remove the TransformStream usage - you're not modifying the response body so it isn't needed
k
fetching audio file might take more than 10ms ,
k
10ms is CPU time, not wall-clock time.
You're not doing any compute whilst waiting for a response to a subrequest.
k
let me try
Works now
but not seekable