Skip to content

Commit

Permalink
fix(readRawBody): handle body as object (#403)
Browse files Browse the repository at this point in the history
  • Loading branch information
igorjacauna authored Jun 20, 2023
1 parent 5a3d0e8 commit add032a
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 3 deletions.
12 changes: 9 additions & 3 deletions src/utils/body.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,9 +30,15 @@ export function readRawBody<E extends Encoding = "utf8">(
(event.node.req as any)[RawBodySymbol] ||
(event.node.req as any).body; /* unjs/unenv #8 */
if (_rawBody) {
const promise = Promise.resolve(_rawBody).then((_resolved) =>
Buffer.isBuffer(_resolved) ? _resolved : Buffer.from(_resolved)
);
const promise = Promise.resolve(_rawBody).then((_resolved) => {
if (Buffer.isBuffer(_resolved)) {
return _resolved;
}
if (_resolved.constructor === Object) {
return Buffer.from(JSON.stringify(_resolved));
}
return Buffer.from(_resolved);
});
return encoding
? promise.then((buff) => buff.toString(encoding))
: (promise as Promise<any>);
Expand Down
20 changes: 20 additions & 0 deletions test/body.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -194,6 +194,26 @@ describe("", () => {
expect(result.text).toBe("200");
});

it("handle readBody with Object type (unenv)", async () => {
app.use(
"/",
eventHandler(async (event) => {
// Emulate unenv
// @ts-ignore
event.node.req.body = { test: 1 };

const body = await readBody(event);
expect(body).toMatchObject({ test: 1 });

return "200";
})
);

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

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

it("handle readRawBody with array buffer type (unenv)", async () => {
app.use(
"/",
Expand Down

0 comments on commit add032a

Please sign in to comment.