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

feat: add readFormData util #421

Merged
merged 5 commits into from
Jul 24, 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
17 changes: 17 additions & 0 deletions src/utils/body.ts
Original file line number Diff line number Diff line change
Expand Up @@ -134,6 +134,23 @@ export async function readMultipartFormData(event: H3Event) {
return parseMultipartData(body, boundary);
}

/**
* Constructs a FormData object from an event.
* @param event {H3Event}
* @returns {FormData}
*
* ```ts
* const eventHandler = event => {
* const formData = await readFormData(event)
* const email = formData.get("email")
* const password = formData.get("password")
* }
* ```
*/
export async function readFormData(event: H3Event) {
return await event.request.formData();
}

// --- Internal ---

function _parseJSON(body = "", strict: boolean) {
Expand Down
25 changes: 25 additions & 0 deletions test/utils.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import {
getMethod,
getQuery,
getRequestURL,
readFormData,
} from "../src";

describe("", () => {
Expand Down Expand Up @@ -158,4 +159,28 @@ describe("", () => {
expect((await request.head("/post")).status).toBe(200);
});
});

const below18 = Number.parseInt(process.version.slice(1).split(".")[0]) < 18;
describe.skipIf(below18)("readFormData", () => {
it("can handle form as FormData in event handler", async () => {
app.use(
"/",
eventHandler(async (event) => {
const formData = await readFormData(event);
const user = formData.get("user");
expect(formData instanceof FormData).toBe(true);
expect(user).toBe("john");
return { user };
})
);

const result = await request
.post("/api/test")
.set("content-type", "application/x-www-form-urlencoded")
.field("user", "john");

expect(result.status).toBe(200);
expect(result.body).toMatchObject({ user: "john" });
});
});
});