Skip to content

Commit

Permalink
fix(getRequestWebStream): reuse buffered body if available (#616)
Browse files Browse the repository at this point in the history
Co-authored-by: Pooya Parsa <pooya@pi0.io>
  • Loading branch information
oscartbeaumont and pi0 authored Jan 15, 2024
1 parent 845eeca commit 751fa45
Showing 1 changed file with 36 additions and 16 deletions.
52 changes: 36 additions & 16 deletions src/utils/body.ts
Original file line number Diff line number Diff line change
Expand Up @@ -256,23 +256,43 @@ export function getRequestWebStream(
if (!PayloadMethods.includes(event.method)) {
return;
}
return (
event.web?.request?.body ||
(event._requestBody as ReadableStream) ||
new ReadableStream({
start: (controller) => {
event.node.req.on("data", (chunk) => {
controller.enqueue(chunk);
});
event.node.req.on("end", () => {
controller.close();
});
event.node.req.on("error", (err) => {
controller.error(err);
});

const bodyStream = event.web?.request?.body || event._requestBody;
if (bodyStream) {
return bodyStream as ReadableStream;
}

// Use provided body (same as readBody)
const _hasRawBody =
RawBodySymbol in event.node.req ||
"rawBody" in event.node.req /* firebase */ ||
"body" in event.node.req /* unenv */ ||
"__unenv__" in event.node.req;
if (_hasRawBody) {
return new ReadableStream({
async start(controller) {
const _rawBody = await readRawBody(event, false);
if (_rawBody) {
controller.enqueue(_rawBody);
}
controller.close();
},
})
);
});
}

return new ReadableStream({
start: (controller) => {
event.node.req.on("data", (chunk) => {
controller.enqueue(chunk);
});
event.node.req.on("end", () => {
controller.close();
});
event.node.req.on("error", (err) => {
controller.error(err);
});
},
});
}

// --- Internal ---
Expand Down

0 comments on commit 751fa45

Please sign in to comment.