Skip to content
Myr

fix: make that `c.req.parseBody` parses only `FormData` (#487)

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 20e8bac · Browse files · 6 files+61 added−110 removed
This commit

State

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

Diff stats

6 files+61 added−110 removed

  • tests:+31 added−56 removed
  • other:+30 added−54 removed

6 files+61 added−110 removed

modified:deno_dist/utils/body.ts+10 added-22 removed
modified:deno_dist/request.ts+5 added-5 removed
modified:src/utils/body.test.ts+16 added-33 removed
modified:src/utils/body.ts+10 added-22 removed
1export async function parseBody<T = any>(r: Request | Response): Promise<T> {2 let body: any34 const contentType = r.headers.get('Content-Type') || ''56 if (contentType.includes('application/json')) {7 let jsonBody = {}8 try {9 jsonBody = await r.json()10 } catch {} // Do nothing11 body = jsonBody12 } else if (contentType.includes('application/text')) {13 body = await r.text()14 } else if (contentType.startsWith('text')) {15 body = await r.text()16 } else if (contentType.includes('form')) {1export async function parseBody(r: Request | Response): Promise<Record<string, string | File>> {2 let body: Record<string, string | File> = {}3 const contentType = r.headers.get('Content-Type')4 if (5 contentType &&6 (contentType.startsWith('multipart/form-data') ||7 contentType === 'application/x-www-form-urlencoded')8 ) {9 const form: Record<string, string | File> = {}18 const data = [...(await r.formData())].reduce((acc, cur) => {10 body = [...(await r.formData())].reduce((acc, cur) => {11 acc[cur[0]] = cur[1]12 return acc13 }, form)22 body = data23 } else {24 body = await r.arrayBuffer()14 }2627 return body as T15 return body16}
modified:src/hono.test.ts+15 added-23 removed
961 unmodified lines
962963describe('Parse Body', () => {964 const app = new Hono()965966 type Payload = {967 message: string968 }969966 app.post('/json', async (c) => {967 return c.json(await c.req.parseBody(), 200)968 })973 app.post('/text', async (c) => {974 return c.text((await c.req.parseBody()) as string, 200)975 })969 app.post('/form', async (c) => {970 return c.json(await c.req.parseBody(), 200)971 })972973 it('POST with JSON', async () => {981 const payload: Payload = { message: 'hello hono' }974 const req = new Request('http://localhost/json', {975 method: 'POST',984 body: JSON.stringify(payload),976 body: JSON.stringify({ message: 'hello hono' }),977 headers: new Headers({ 'Content-Type': 'application/json' }),978 })979 const res = await app.request(req)980 expect(res).not.toBeNull()981 expect(res.status).toBe(200)990 const body = await req.parseBody<Payload>()991 expect(body.message).toBe('hello hono')992 expect(body).toEqual(payload)982 const body = await req.parseBody()983 expect(body).toEqual({})984 })985995 it('POST with text', async () => {996 const payload = 'hello'997 const req = new Request('http://localhost/text', {986 it('POST with `multipart/form-data`', async () => {987 const formData = new FormData()988 formData.append('message', 'hello')989 const req = new Request('https://localhost/form', {990 method: 'POST',999 body: 'hello',1000 headers: new Headers({ 'Content-Type': 'application/text' }),991 body: formData,992 })993994 const res = await app.request(req)995 expect(res).not.toBeNull()996 expect(res.status).toBe(200)1005 expect(await req.parseBody()).toEqual(payload)1006 expect(await res.text()).toEqual(payload)997 expect(await req.parseBody()).toEqual({ message: 'hello' })998 expect(await res.json()).toEqual({ message: 'hello' })999 })10001009 it('POST with form', async () => {1010 const formData = new URLSearchParams()1011 formData.append('message', 'hello')1001 it('POST with `application/x-www-form-urlencoded`', async () => {1002 const searchParam = new URLSearchParams()1003 searchParam.append('message', 'hello')1004 const req = new Request('https://localhost/form', {1005 method: 'POST',1014 body: formData,1006 body: searchParam,1007 headers: {1008 'Content-Type': 'application/x-www-form-urlencoded',1009 },1010 })
26 unmodified lines
modified:src/request.ts+5 added-5 removed
23 unmodified lines
24 cookie: {25 (name: string): string26 (): Cookie27 }28 parsedBody?: Promise<any>28 parsedBody?: Promise<Record<string, string | File>>29 parseBody: {30 <T = any>(): Promise<T>30 (): Promise<Record<string, string | File>>31 }32 }33}34
62 unmodified lines
97 return obj98 }99 } as InstanceType<typeof Request>['cookie']100101 Request.prototype.parseBody = function <T = any>(this: Request): Promise<T> {102 let body: Promise<T>101 Request.prototype.parseBody = function (this: Request): Promise<Record<string, string | File>> {102 let body: Promise<Record<string, string | File>>103 if (!this.parsedBody) {104 body = parseBody<T>(this)104 body = parseBody(this)105 this.parsedBody = body106 } else {107 body = this.parsedBody108 }
3 unmodified lines