oak icon indicating copy to clipboard operation
oak copied to clipboard

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

Open bodograumann opened this issue 3 months ago • 1 comments

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. [email protected] seems to be missing the v in front of the version ;-)

bodograumann avatar Mar 11 '24 16:03 bodograumann

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.

bodograumann avatar Mar 12 '24 07:03 bodograumann