Skip to content
Myr

fix(validator): use cached body for `json` and `form` validation (#2392)

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

* fix(validator): use cached body for `json` and `form` validation * denoify * teak

authored by Yusuke Wada · committed by GitHub · parent d7e9706 · Browse files · 3 files+138 added−78 removed
This commit

State

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

Diff stats

3 files+138 added−78 removed

  • tests:+66 added−46 removed
  • other:+72 added−32 removed

3 files+138 added−78 removed

modified:deno_dist/validator/validator.ts+36 added-16 removed
modified:src/validator/validator.test.ts+66 added-46 removed
171 unmodified lines
172 })173})174175describe('Cached contents', () => {176 describe('json', () => {176 const app = new Hono()177 const app = new Hono()178 const bodyTypes = ['json', 'text', 'arrayBuffer', 'blob']179180 for (const type of bodyTypes) {181 app.post(178 app.post(179 '/json',180 async (c, next) => {181 await c.req.json()182 await next()183 },184 validator('json', (value) => {185 return value186 }),187 async (c) => {188 const data = await c.req.json()189 return c.json(data, 200)182 `/${type}`,183 async (c, next) => {184 // @ts-expect-error not type safe185 await c.req[type]()186 await next()187 },188 validator('json', (value) => {189 return value190 }),191 async (c) => {192 const data = await c.req.json()193 return c.json(data, 200)194 }195 )196 }191 )197193 app.post(194 '/form',195 async (c, next) => {196 await c.req.formData()197 await next()198 },199 validator('form', (value) => {200 return value201 }),202 async (c) => {203 return c.json({ message: 'OK' }, 200)198 for (const type of bodyTypes) {199 const endpoint = `/${type}`200 it(`Should return the cached JSON content - ${endpoint}`, async () => {201 const res = await app.request(endpoint, {202 method: 'POST',203 body: JSON.stringify({ message: 'Hello' }),204 headers: {205 'Content-Type': 'application/json',206 },207 })208 expect(res.status).toBe(200)209 expect(await res.json()).toEqual({ message: 'Hello' })210 })211 }205 )206207 it('Should return the cached JSON content', async () => {208 const res = await app.request('/json', {209 method: 'POST',210 body: JSON.stringify({ message: 'Hello' }),211 headers: {212 'Content-Type': 'application/json',213 },214 })215 expect(res.status).toBe(200)216 expect(await res.json()).toEqual({ message: 'Hello' })212 })213214 describe('form', () => {215 const app = new Hono()216 const bodyTypes = ['formData', 'text', 'arrayBuffer', 'blob']217218 for (const type of bodyTypes) {219 app.post(220 `/${type}`,221 async (c, next) => {222 // @ts-expect-error not type safe223 await c.req[type]()224 await next()225 },226 validator('form', (value) => {227 return value228 }),229 async (c) => {230 return c.json({ message: 'OK' }, 200)231 }232 )233 }234235 for (const type of bodyTypes) {236 const endpoint = `/${type}`219 it('Should return the cached form content', async () => {220 const form = new FormData()221 form.append('message', 'Hello')222 const res = await app.request('/form', {223 method: 'POST',224 body: form,225 })226 expect(res.status).toBe(200)227 expect(await res.json()).toEqual({ message: 'OK' })237 it(`Should return the cached FormData content - ${endpoint}`, async () => {238 const form = new FormData()239 form.append('message', 'Hello')240 const res = await app.request(endpoint, {241 method: 'POST',242 body: form,243 })244 expect(res.status).toBe(200)245 expect(await res.json()).toEqual({ message: 'OK' })246 })247 }248 })249})250251describe('Validator middleware with a custom validation function', () => {
697 unmodified lines
modified:src/validator/validator.ts+36 added-16 removed
58 unmodified lines
59): MiddlewareHandler<E, P, V> => {60 return async (c, next) => {61 let value = {}62 const contentType = c.req.header('Content-Type')63 const bodyTypes = ['text', 'arrayBuffer', 'blob']6465 switch (target) {66 case 'json':67 if (!contentType || !contentType.startsWith('application/json')) {68 const message = `Invalid HTTP header: Content-Type=${contentType}`69 throw new HTTPException(400, { message })70 }7172 if (c.req.bodyCache.json) {71 value = await c.req.bodyCache.json73 value = c.req.bodyCache.json74 break75 }74 /**75 * Get the arrayBuffer, create JSON object via Response, and cache the arrayBuffer in the c.req.bodyCache if there is no cached content in c.req.bodyCache.json.76 */7677 try {78 const arrayBuffer = c.req.bodyCache.arrayBuffer ?? (await c.req.raw.arrayBuffer())78 let arrayBuffer: ArrayBuffer | undefined = undefined79 for (const type of bodyTypes) {80 // @ts-expect-error bodyCache[type] is not typed81 const body = c.req.bodyCache[type]82 if (body) {83 arrayBuffer = await new Response(await body).arrayBuffer()84 break85 }86 }87 arrayBuffer ??= await c.req.raw.arrayBuffer()88 value = await new Response(arrayBuffer).json()89 c.req.bodyCache.json = value90 c.req.bodyCache.arrayBuffer = arrayBuffer91 } catch {
1 unmodified line
93 throw new HTTPException(400, { message })94 }95 break96 case 'form': {97 if (!contentType) {98 break99 }100101 if (c.req.bodyCache.formData) {102 value = c.req.bodyCache.formData103 break104 }105106 try {93 const contentType = c.req.header('Content-Type')94 if (contentType) {95 const arrayBuffer = c.req.bodyCache.arrayBuffer ?? (await c.req.raw.arrayBuffer())96 const formData = await bufferToFormData(arrayBuffer, contentType)97 const form: BodyData = {}98 formData.forEach((value, key) => {99 form[key] = value100 })101 value = form102 c.req.bodyCache.formData = formData103 c.req.bodyCache.arrayBuffer = arrayBuffer107 let arrayBuffer: ArrayBuffer | undefined = undefined108 for (const type of bodyTypes) {109 // @ts-expect-error bodyCache[type] is not typed110 const body = c.req.bodyCache[type]111 if (body) {112 arrayBuffer = await new Response(await body).arrayBuffer()113 break114 }115 }116 arrayBuffer ??= await c.req.arrayBuffer()117 const formData = await bufferToFormData(arrayBuffer, contentType)118 const form: BodyData = {}119 formData.forEach((value, key) => {120 form[key] = value121 })122 value = form123 c.req.bodyCache.formData = formData124 c.req.bodyCache.arrayBuffer = arrayBuffer125 } catch (e) {126 let message = 'Malformed FormData request.'127 message += e instanceof Error ? ` ${e.message}` : ` ${String(e)}`128 throw new HTTPException(400, { message })
32 unmodified lines