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(readBody, readRawBody): handle raw body as buffer #366

Merged
merged 4 commits into from
Mar 28, 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
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