From add032a219443c7e2a92fd7e46846cca41adeac9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C3=8Dgor=20Jaca=C3=BAna?= <459127+igorjacauna@users.noreply.github.com> Date: Tue, 20 Jun 2023 16:58:27 -0400 Subject: [PATCH] fix(readRawBody): handle body as object (#403) --- src/utils/body.ts | 12 +++++++++--- test/body.test.ts | 20 ++++++++++++++++++++ 2 files changed, 29 insertions(+), 3 deletions(-) diff --git a/src/utils/body.ts b/src/utils/body.ts index 52cd9150..382d7b99 100644 --- a/src/utils/body.ts +++ b/src/utils/body.ts @@ -30,9 +30,15 @@ export function readRawBody( (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); diff --git a/test/body.test.ts b/test/body.test.ts index 53069d97..24e0b877 100644 --- a/test/body.test.ts +++ b/test/body.test.ts @@ -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( "/",