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
Provenance
- Commit
128a59a- Tree
0900437- Author
Yusuke Wada <yusuke@kamawada.com>- Committer
GitHub <noreply@github.com>- Parent
20e8bac
6 files changed+61 added−110 removed
modified:deno_dist/utils/body.ts+10 added-22 removed
1234567891011121314151612345678918101112132223241426271516export async function parseBody<T = any>(r: Request | Response): Promise<T> { let body: any
const contentType = r.headers.get('Content-Type') || ''
if (contentType.includes('application/json')) { let jsonBody = {} try { jsonBody = await r.json() } catch {} // Do nothing body = jsonBody } else if (contentType.includes('application/text')) { body = await r.text() } else if (contentType.startsWith('text')) { body = await r.text() } else if (contentType.includes('form')) {export async function parseBody(r: Request | Response): Promise<Record<string, string | File>> { let body: Record<string, string | File> = {} const contentType = r.headers.get('Content-Type') if ( contentType && (contentType.startsWith('multipart/form-data') || contentType === 'application/x-www-form-urlencoded') ) { const form: Record<string, string | File> = {} const data = [...(await r.formData())].reduce((acc, cur) => { body = [...(await r.formData())].reduce((acc, cur) => { acc[cur[0]] = cur[1] return acc }, form) body = data } else { body = await r.arrayBuffer() }
return body as T return body}modified:deno_dist/request.ts+5 added-5 removed
23 unmodified lines2425262728282930303132333462 unmodified lines9798991001011021011021031041041051061071083 unmodified lines23 unmodified lines cookie: { (name: string): string (): Cookie } parsedBody?: Promise<any> parsedBody?: Promise<Record<string, string | File>> parseBody: { <T = any>(): Promise<T> (): Promise<Record<string, string | File>> } }}
62 unmodified lines return obj } } as InstanceType<typeof Request>['cookie']
Request.prototype.parseBody = function <T = any>(this: Request): Promise<T> { let body: Promise<T> Request.prototype.parseBody = function (this: Request): Promise<Record<string, string | File>> { let body: Promise<Record<string, string | File>> if (!this.parsedBody) { body = parseBody<T>(this) body = parseBody(this) this.parsedBody = body } else { body = this.parsedBody }3 unmodified linesmodified:src/utils/body.test.ts+16 added-33 removed
12345634567889910111112131414151615161718191819202122232425262728292021222324252627373839404142434445464728293031323334353637import { parseBody } from './body'
describe('Parse Body Middleware', () => { it('should parse JSON', async () => { const payload = { message: 'hello hono' } const req = new Request('http://localhost/json', {describe('Parse Body Util', () => { it('should parse `multipart/form-data`', async () => { const data = new FormData() data.append('message', 'hello') const req = new Request('https://localhost/form', { method: 'POST', body: JSON.stringify(payload), headers: new Headers({ 'Content-Type': 'application/json' }), body: data, // `Content-Type` header must not be set. }) expect(await parseBody(req)).toEqual(payload) expect(await parseBody(req)).toEqual({ message: 'hello' }) })
it('should parse Text', async () => { const payload = 'hello' const req = new Request('http://localhost/text', { it('should parse `x-www-form-urlencoded`', async () => { const searchParams = new URLSearchParams() searchParams.append('message', 'hello') const req = new Request('https://localhost/search', { method: 'POST', body: 'hello', headers: new Headers({ 'Content-Type': 'application/text' }), }) expect(await parseBody(req)).toEqual(payload) })
it('should parse Form', async () => { const formData = new URLSearchParams() formData.append('message', 'hello') const req = new Request('https://localhost/form', { method: 'POST', body: formData, body: searchParams, headers: { 'Content-Type': 'application/x-www-form-urlencoded', }, }) expect(await parseBody(req)).toEqual({ message: 'hello' }) })
it('should parse Response body ', async () => { const payload = 'hello' const res = new Response(payload, { headers: { 'Content-Type': 'text/plain', }, }) expect(await parseBody(res)).toEqual(payload) })
it('should return blank object if JSON body is nothing', async () => { it('should return blank object if body is JSON', async () => { const payload = { message: 'hello hono' } const req = new Request('http://localhost/json', { method: 'POST', body: JSON.stringify(payload), headers: new Headers({ 'Content-Type': 'application/json' }), }) expect(await parseBody(req)).toEqual({}) })})modified:src/utils/body.ts+10 added-22 removed
1-export async function parseBody<T = any>(r: Request | Response): Promise<T> {2- let body: any3-4- const contentType = r.headers.get('Content-Type') || ''5-6- 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')) {1+export 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 }26-27- return body as T15+ return body16 }modified:src/hono.test.ts+15 added-23 removed
961 unmodified lines962 963 describe('Parse Body', () => {964 const app = new Hono()965 966- type Payload = {967- message: string968- }969-966 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 })972 973 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 })985 995- 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 })993+994 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 })1000 1009- 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 linesmodified:src/request.ts+5 added-5 removed
23 unmodified lines24 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 lines97 return obj98 }99 } as InstanceType<typeof Request>['cookie']100 101- 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