From 73f090b4a584f6b93299ab4e7f3f73b86727e8c3 Mon Sep 17 00:00:00 2001 From: Pooya Parsa Date: Thu, 31 Mar 2022 20:26:36 +0200 Subject: [PATCH] feat(useBody): support `application/x-www-form-urlencoded` Co-Authored-By florent giraud closes #44 --- src/utils/body.ts | 10 +++++++++- test/body.test.ts | 18 +++++++++++++++++- 2 files changed, 26 insertions(+), 2 deletions(-) diff --git a/src/utils/body.ts b/src/utils/body.ts index 658e53aa..20136cb9 100644 --- a/src/utils/body.ts +++ b/src/utils/body.ts @@ -55,7 +55,15 @@ export async function useBody (event: CompatibilityEvent): Promise { if (ParsedBodySymbol in event.req) { return (event.req as any)[ParsedBodySymbol] } - const body = await useRawBody(event) + + // TODO: Handle buffer + const body = await useRawBody(event) as string + + if (event.req.headers['content-type'] === 'application/x-www-form-urlencoded') { + const parsedForm = Object.fromEntries(new URLSearchParams(body)) + return parsedForm as unknown as T + } + const json = destr(body) as T (event.req as any)[ParsedBodySymbol] = json return json diff --git a/test/body.test.ts b/test/body.test.ts index fd0a8003..b188bd53 100644 --- a/test/body.test.ts +++ b/test/body.test.ts @@ -28,7 +28,7 @@ describe('', () => { }) }) - describe('useJSON', () => { + describe('useBody', () => { it('can parse json payload', async () => { app.use('/', async (request) => { const body = await useBody(request) @@ -47,5 +47,21 @@ describe('', () => { expect(result.text).toBe('200') }) + + it('parse the form encoded into an object', async () => { + app.use('/', async (request) => { + const body = await useBody(request) + expect(body).toMatchObject({ + field: 'value', + another: 'true', + number: '20' + }) + return '200' + }) + const result = await request.post('/api/test') + .send('field=value&another=true&number=20') + + expect(result.text).toBe('200') + }) }) })