Skip to content
Myr

fix: enable passing Generics to c.req.parseBody, default is any (#481)

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by Yusuke Wada · committed by GitHub · parent ddfe07e · Browse files · 5 files+48 added−35 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

5 files+48 added−35 removed

  • tests:+8 added−3 removed
  • other:+40 added−32 removed

5 files+48 added−35 removed

modified:deno_dist/utils/body.ts+11 added-10 removed
modified:deno_dist/request.ts+9 added-6 removed
modified:src/utils/body.ts+11 added-10 removed
modified:src/hono.test.ts+8 added-3 removed
961 unmodified lines
962963describe('Parse Body', () => {964 const app = new Hono()965966 type Payload = {967 message: string968 }969970 app.post('/json', async (c) => {971 return c.json(await c.req.parseBody(), 200)972 })973 app.post('/text', async (c) => {
3 unmodified lines
977 return c.json(await c.req.parseBody(), 200)978 })979980 it('POST with JSON', async () => {977 const payload = { message: 'hello hono' }981 const payload: Payload = { message: 'hello hono' }982 const req = new Request('http://localhost/json', {983 method: 'POST',984 body: JSON.stringify(payload),985 headers: new Headers({ 'Content-Type': 'application/json' }),986 })987 const res = await app.request(req)988 expect(res).not.toBeNull()989 expect(res.status).toBe(200)986 expect(await req.parseBody()).toEqual(payload)987 expect(await res.json()).toEqual(payload)990 const body = await req.parseBody<Payload>()991 expect(body.message).toBe('hello hono')992 expect(body).toEqual(payload)993 })994995 it('POST with text', async () => {996 const payload = 'hello'
48 unmodified lines
modified:src/request.ts+9 added-6 removed
1import { parseBody } from './utils/body'2import type { Body } from './utils/body'2import type { Cookie } from './utils/cookie'3import { parse } from './utils/cookie'45declare global {
18 unmodified lines
24 cookie: {25 (name: string): string26 (): Cookie27 }29 parsedBody?: Promise<Body>28 parsedBody?: Promise<any>29 parseBody: {31 (): Promise<Body>30 <T = any>(): Promise<T>31 }32 }33}34
62 unmodified lines
97 return obj98 }99 } as InstanceType<typeof Request>['cookie']100102 Request.prototype.parseBody = function (this: Request) {101 Request.prototype.parseBody = function <T = any>(this: Request): Promise<T> {102 let body: Promise<T>103 if (!this.parsedBody) {104 this.parsedBody = parseBody(this)104 body = parseBody<T>(this)105 this.parsedBody = body106 } else {107 body = this.parsedBody108 }106 return this.parsedBody109 return body110 } as InstanceType<typeof Request>['parseBody']111}