Skip to content

Commit

Permalink
fix(readBody, readRawBody): handle raw body as buffer (#366)
Browse files Browse the repository at this point in the history
* fix: handle `Buffer` in `readBody`

* add failing test

* fix it within readRawBody

* simplify code

---------

Co-authored-by: Pooya Parsa <pooya@pi0.io>
  • Loading branch information
johannschopplich and pi0 authored Mar 28, 2023
1 parent ba64f60 commit 74a2e6d
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 9 deletions.
16 changes: 7 additions & 9 deletions src/utils/body.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,16 +25,15 @@ export function readRawBody<E extends Encoding = "utf8">(
// Ensure using correct HTTP method before attempt to read payload
assertMethod(event, PayloadMethods);

if (RawBodySymbol in event.node.req) {
const promise = Promise.resolve((event.node.req as any)[RawBodySymbol]);
// Reuse body if already read
const _rawBody =
(event.node.req as any)[RawBodySymbol] ||
(event.node.req as any).body; /* unjs/unenv #8 */
if (_rawBody) {
const promise = Promise.resolve(_rawBody);
return encoding ? promise.then((buff) => buff.toString(encoding)) : promise;
}

// Workaround for unenv issue https://github.com/unjs/unenv/issues/8
if ("body" in event.node.req) {
return Promise.resolve((event.node.req as any).body);
}

if (!Number.parseInt(event.node.req.headers["content-length"] || "")) {
return Promise.resolve(undefined);
}
Expand Down Expand Up @@ -79,8 +78,7 @@ export async function readBody<T = any>(event: H3Event): Promise<T> {
return (event.node.req as any)[ParsedBodySymbol];
}

// TODO: Handle buffer
const body = (await readRawBody(event)) as string;
const body = await readRawBody(event, "utf8");

if (
event.node.req.headers["content-type"] ===
Expand Down
20 changes: 20 additions & 0 deletions test/body.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -174,6 +174,26 @@ describe("", () => {
expect(result.text).toBe("200");
});

it("handle raw body with buffer type (unenv)", async () => {
app.use(
"/",
eventHandler(async (event) => {
// Emulate unenv
// @ts-ignore
event.node.req.body = Buffer.from("test");

const body = await readBody(event);
expect(body).toMatchObject("test");

return "200";
})
);

const result = await request.post("/api/test").send();

expect(result.text).toBe("200");
});

it("parses multipart form data", async () => {
app.use(
"/",
Expand Down

0 comments on commit 74a2e6d

Please sign in to comment.