Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(readRawBody): handle body as object #403

Merged
merged 2 commits into from
Jun 20, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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