Skip to content

Commit 57dcba8

Browse files
authored
feat: add readFormData util (#421)
1 parent 5c4521f commit 57dcba8

2 files changed

Lines changed: 42 additions & 0 deletions

File tree

src/utils/body.ts

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -134,6 +134,23 @@ export async function readMultipartFormData(event: H3Event) {
134134
return parseMultipartData(body, boundary);
135135
}
136136

137+
/**
138+
* Constructs a FormData object from an event.
139+
* @param event {H3Event}
140+
* @returns {FormData}
141+
*
142+
* ```ts
143+
* const eventHandler = event => {
144+
* const formData = await readFormData(event)
145+
* const email = formData.get("email")
146+
* const password = formData.get("password")
147+
* }
148+
* ```
149+
*/
150+
export async function readFormData(event: H3Event) {
151+
return await event.request.formData();
152+
}
153+
137154
// --- Internal ---
138155

139156
function _parseJSON(body = "", strict: boolean) {

test/utils.test.ts

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ import {
1111
getMethod,
1212
getQuery,
1313
getRequestURL,
14+
readFormData,
1415
} from "../src";
1516

1617
describe("", () => {
@@ -158,4 +159,28 @@ describe("", () => {
158159
expect((await request.head("/post")).status).toBe(200);
159160
});
160161
});
162+
163+
const below18 = Number.parseInt(process.version.slice(1).split(".")[0]) < 18;
164+
describe.skipIf(below18)("readFormData", () => {
165+
it("can handle form as FormData in event handler", async () => {
166+
app.use(
167+
"/",
168+
eventHandler(async (event) => {
169+
const formData = await readFormData(event);
170+
const user = formData.get("user");
171+
expect(formData instanceof FormData).toBe(true);
172+
expect(user).toBe("john");
173+
return { user };
174+
})
175+
);
176+
177+
const result = await request
178+
.post("/api/test")
179+
.set("content-type", "application/x-www-form-urlencoded")
180+
.field("user", "john");
181+
182+
expect(result.status).toBe(200);
183+
expect(result.body).toMatchObject({ user: "john" });
184+
});
185+
});
161186
});

0 commit comments

Comments
 (0)