oakserver / oak

A middleware framework for handling HTTP with Deno, Node, Bun and Cloudflare Workers 🐿️ 🦕
https://oakserver.org
MIT License
5.09k stars 231 forks source link

Use body and relay it via proxy middleware in oak v13+ #642

Open bodograumann opened 6 months ago

bodograumann commented 6 months ago

In our application there are two independant places where the request body needs to be accessed. In one place we are reading it as json, in the other we are forwarding the whole request with the proxy middleware. In oak 12 the following would work for the direct access and still allow proxy to use the body.

const stream = context.request.body({ type: "stream" }).value;
const fakeResponse = new Response(stream);
const data = await fakeResponse.json();

For oak 14.2.0 I tried using const stream = context.request.body.stream, but this just leads to the error:

TypeError: ReadableStream is locked or disturbed

Before diving into the new code myself, I wanted to ask whether there is a known way to read the request body, while still keeping it intact for the proxy middleware?


Btw. oak@14.2.0 seems to be missing the v in front of the version ;-)

bodograumann commented 6 months ago

It seems previously the approach worked, because { type: "stream" } would .tee() the stream and make it reusable that way: https://github.com/oakserver/oak/blob/v12.6.2/body.ts#L413-L417

Unfortunately this does not seem possible from the outside with the current code. Can we somehow get the old behaviour back? For compatibility with the old version it would make sense to use .tee() in get stream(), but maybe the side-effect is not wanted anymore? Alternatively I could imagine a new method .teeStream that duplicates the stream. What do you think @kitsonk ? I'd be happy to create a PR.