Skip to content

Commit

Permalink
feat(useBody): support application/x-www-form-urlencoded
Browse files Browse the repository at this point in the history
Co-Authored-By florent giraud <hello@florent.dev>

closes #44
  • Loading branch information
pi0 committed Mar 31, 2022
1 parent d75f6a1 commit 73f090b
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 2 deletions.
10 changes: 9 additions & 1 deletion src/utils/body.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,15 @@ export async function useBody<T=any> (event: CompatibilityEvent): Promise<T> {
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
Expand Down
18 changes: 17 additions & 1 deletion test/body.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ describe('', () => {
})
})

describe('useJSON', () => {
describe('useBody', () => {
it('can parse json payload', async () => {
app.use('/', async (request) => {
const body = await useBody(request)
Expand All @@ -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')
})
})
})

0 comments on commit 73f090b

Please sign in to comment.