diff --git a/src/request.test.ts b/src/request.test.ts index 9163f2a38..5be203367 100644 --- a/src/request.test.ts +++ b/src/request.test.ts @@ -1,6 +1,10 @@ import { HonoRequest } from './request' import type { RouterRoute } from './types' +type RecursiveRecord = { + [key in K]: T | RecursiveRecord +} + describe('Query', () => { test('req.query() and req.queries()', () => { const rawRequest = new Request('http://localhost?page=2&tag=A&tag=B') @@ -251,4 +255,61 @@ describe('Body methods with caching', () => { expect(async () => await req.arrayBuffer()).not.toThrow() expect(async () => await req.blob()).not.toThrow() }) + + describe('req.parseBody()', async () => { + it('should parse form data', async () => { + const data = new FormData() + data.append('foo', 'bar') + const req = new HonoRequest( + new Request('http://localhost', { + method: 'POST', + body: data, + }) + ) + expect((await req.parseBody())['foo']).toBe('bar') + expect((await req.parseBody())['foo']).toBe('bar') + expect(async () => await req.text()).not.toThrow() + expect(async () => await req.arrayBuffer()).not.toThrow() + expect(async () => await req.blob()).not.toThrow() + }) + + describe('Return type', () => { + let req: HonoRequest + beforeEach(() => { + const data = new FormData() + data.append('foo', 'bar') + req = new HonoRequest( + new Request('http://localhost', { + method: 'POST', + body: data, + }) + ) + }) + + it('without options', async () => { + expectTypeOf((await req.parseBody())['key']).toEqualTypeOf() + }) + + it('{all: true}', async () => { + expectTypeOf((await req.parseBody({ all: true }))['key']).toEqualTypeOf< + string | File | (string | File)[] + >() + }) + + it('{dot: true}', async () => { + expectTypeOf((await req.parseBody({ dot: true }))['key']).toEqualTypeOf< + string | File | RecursiveRecord + >() + }) + + it('{all: true, dot: true}', async () => { + expectTypeOf((await req.parseBody({ all: true, dot: true }))['key']).toEqualTypeOf< + | string + | File + | (string | File)[] + | RecursiveRecord + >() + }) + }) + }) }) diff --git a/src/request.ts b/src/request.ts index 7c028aee5..9002436ae 100644 --- a/src/request.ts +++ b/src/request.ts @@ -183,7 +183,11 @@ export class HonoRequest

{ * ``` * @see https://hono.dev/api/request#parsebody */ - async parseBody(options?: ParseBodyOptions): Promise { + async parseBody, T extends BodyData>( + options?: Options + ): Promise + async parseBody(options?: Partial): Promise + async parseBody(options?: Partial): Promise { if (this.bodyCache.parsedBody) { return this.bodyCache.parsedBody as T }