Skip to content
Myr

fix(validator): cache `arrayBuffer` to use after validation (#1393)

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

* wip * fix(validator): cache `arrayBuffer` to use after validation * denoify * refactor * denoify * make it `bufferToFormData()` in utils/buffer.ts

authored by Yusuke Wada · committed by GitHub · parent 0316bba · Browse files · 10 files+217 added−33 removed
This commit

State

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

Diff stats

10 files+217 added−33 removed

  • tests:+39 added−3 removed
  • other:+178 added−30 removed

10 files+217 added−33 removed

modified:deno_dist/utils/body.ts+11 added-7 removed
modified:deno_dist/utils/buffer.ts+31 added
modified:deno_dist/validator/validator.ts+24 added-3 removed
modified:deno_dist/request.ts+23 added-5 removed
14 unmodified lines
15import { parse } from './utils/cookie.ts'16import type { UnionToIntersection } from './utils/types.ts'17import { getQueryParam, getQueryParams, decodeURIComponent_ } from './utils/url.ts'1819type BodyType = 'json' | 'text' | 'arrayBuffer' | 'blob' | 'formData'20type BodyCache = Partial<Record<BodyType, any>>19type Body = {20 json: any21 text: string22 arrayBuffer: ArrayBuffer23 blob: Blob24 formData: FormData25}26type BodyCache = Partial<Body & { parsedBody: BodyData }>2728export class HonoRequest<P extends string = '/', I extends Input['out'] = {}> {29 raw: Request3031 private paramData: Record<string, string> | undefined32 private vData: { [K in keyof ValidationTargets]?: {} } // Short name of validatedData33 path: string28 private bodyCache: BodyCache = {}34 bodyCache: BodyCache = {}3536 constructor(37 request: Request,38 path: string = '/',
87 unmodified lines
126 }127 }128129 async parseBody<T extends BodyData = BodyData>(): Promise<T> {124 return await parseBody(this)130 if (this.bodyCache.parsedBody) return this.bodyCache.parsedBody as T131 const parsedBody = await parseBody<T>(this)132 this.bodyCache.parsedBody = parsedBody133 return parsedBody134 }135127 private cachedBody = (key: keyof BodyCache) => {136 private cachedBody = (key: keyof Body) => {137 const { bodyCache, raw } = this138 const cachedBody = bodyCache[key]139 if (cachedBody) return cachedBody140 /**141 * If an arrayBuffer cache is exist,142 * use it for creating a text, json, and others.143 */144 if (bodyCache.arrayBuffer) {145 return (async () => {146 return await new Response(bodyCache.arrayBuffer)[key]()147 })()148 }149 return (bodyCache[key] = raw[key]())150 }151152 json<T = any>(): Promise<T> {
56 unmodified lines
modified:src/utils/body.ts+11 added-7 removed
1 unmodified line
23export type BodyData = Record<string, string | File>45export const parseBody = async <T extends BodyData = BodyData>(6 r: HonoRequest | Request6 request: HonoRequest | Request7): Promise<T> => {8 let body: BodyData = {}9 const contentType = r.headers.get('Content-Type')9 const contentType = request.headers.get('Content-Type')1011 if (12 contentType &&13 (contentType.startsWith('multipart/form-data') ||14 contentType.startsWith('application/x-www-form-urlencoded'))15 ) {16 const formData = await request.formData()17 if (formData) {15 const form: BodyData = {}16 ;(await r.formData()).forEach((value, key) => {17 form[key] = value18 })19 body = form18 const form: BodyData = {}19 formData.forEach((value, key) => {20 form[key] = value21 })22 body = form23 }24 }25 return body as T26}
modified:src/utils/buffer.test.ts+25 added-1 removed
1import { SHA256 as sha256CryptoJS } from 'crypto-js'2import { timingSafeEqual, bufferToString } from './buffer'2import { timingSafeEqual, bufferToString, bufferToFormData } from './buffer'34describe('buffer', () => {5 it('positive', async () => {6 expect(
45 unmodified lines
52 const buffer = Uint8Array.from(bytes).buffer53 expect(bufferToString(buffer)).toBe('あいうえお')54 })55})5657describe('bufferToFormData', () => {58 it('Should parse multipart/form-data from ArrayBuffer', () => {59 const encoder = new TextEncoder()60 const testData =61 '--sampleboundary\r\nContent-Disposition: form-data; name="test"\r\n\r\nHello\r\n--sampleboundary--'62 const arrayBuffer = encoder.encode(testData).buffer6364 const result = bufferToFormData(arrayBuffer, 'multipart/form-data; boundary=sampleboundary')6566 expect(result.get('test')).toBe('Hello')67 })6869 it('Should parse application/x-www-form-urlencoded from ArrayBuffer', () => {70 const encoder = new TextEncoder()71 const testData = 'key1=value1&key2=value2'72 const arrayBuffer = encoder.encode(testData).buffer7374 const result = bufferToFormData(arrayBuffer, 'application/x-www-form-urlencoded')7576 expect(result.get('key1')).toBe('value1')77 expect(result.get('key2')).toBe('value2')78 })79})
modified:src/utils/buffer.ts+31 added
45 unmodified lines
46 return enc.decode(buffer)47 }48 return buffer49}5051const _decodeURIComponent = decodeURIComponent5253export const bufferToFormData = (arrayBuffer: ArrayBuffer, contentType: string) => {54 const decoder = new TextDecoder('utf-8')55 const content = decoder.decode(arrayBuffer)56 const formData = new FormData()5758 const boundaryMatch = contentType.match(/boundary=(.+)/)59 const boundary = boundaryMatch ? boundaryMatch[1] : ''6061 if (contentType.startsWith('multipart/form-data') && boundary) {62 const parts = content.split('--' + boundary).slice(1, -1)63 for (const part of parts) {64 const [header, body] = part.split('\r\n\r\n')65 const nameMatch = header.match(/name="([^"]+)"/)66 if (nameMatch) {67 const name = nameMatch[1]68 formData.append(name, body.trim())69 }70 }71 } else if (contentType.startsWith('application/x-www-form-urlencoded')) {72 const pairs = content.split('&')73 for (const pair of pairs) {74 const [key, value] = pair.split('=')75 formData.append(_decodeURIComponent(key), _decodeURIComponent(value))76 }77 }7879 return formData80}
modified:src/validator/validator.test.ts+14 added-2 removed
658 unmodified lines
659 foo: 'bar',660 }661 }),662 async (c) => {663 // `c.req.json` should not throw the error663 // `c.req.json()` should not throw the error664 await c.req.json()665 // `c.req.text()` should not throw the error666 await c.req.text()667 // `c.req.arrayBuffer()` should not throw the error668 await c.req.arrayBuffer()669 // `c.req.blob()` should not throw the error670 await c.req.blob()671 return c.text('foo')672 }673 )674
16 unmodified lines
691 foo: 'bar',692 }693 }),694 async (c) => {689 // `c.req.json` should not throw the error695 // `c.req.parseBody()` should not throw the error696 await c.req.parseBody()697 // `c.req.text()` should not throw the error698 await c.req.text()699 // `c.req.arrayBuffer()` should not throw the error700 await c.req.arrayBuffer()701 // `c.req.blob()` should not throw the error702 await c.req.blob()703 return c.text('foo')704 }705 )706
37 unmodified lines
modified:src/validator/validator.ts+24 added-3 removed
1import type { Context } from '../context'2import { getCookie } from '../helper/cookie'3import type { Env, ValidationTargets, MiddlewareHandler } from '../types'4import type { BodyData } from '../utils/body'5import { bufferToFormData } from '../utils/buffer'67type ValidationTargetKeysWithBody = 'form' | 'json'8type ValidationTargetByMethod<M> = M extends 'get' | 'head' // GET and HEAD request must not have a body content.9 ? Exclude<keyof ValidationTargets, ValidationTargetKeysWithBody>
39 unmodified lines
4950 switch (target) {51 case 'json':52 try {51 value = await c.req.json()53 /**54 * Get the arrayBuffer first, create JSON object via Response,55 * and cache the arrayBuffer in the c.req.bodyCache.56 */57 const arrayBuffer = c.req.bodyCache.arrayBuffer ?? (await c.req.raw.arrayBuffer())58 value = await new Response(arrayBuffer).json()59 c.req.bodyCache.json = value60 c.req.bodyCache.arrayBuffer = arrayBuffer61 } catch {62 console.error('Error: Malformed JSON in request body')63 return c.json(64 {
3 unmodified lines
68 40069 )70 }71 break63 case 'form':64 value = await c.req.parseBody()72 case 'form': {73 const contentType = c.req.header('Content-Type')74 if (contentType) {75 const arrayBuffer = c.req.bodyCache.arrayBuffer ?? (await c.req.raw.arrayBuffer())76 const formData = bufferToFormData(arrayBuffer, contentType)77 const form: BodyData = {}78 formData.forEach((value, key) => {79 form[key] = value80 })81 value = form82 c.req.bodyCache.formData = formData83 c.req.bodyCache.arrayBuffer = arrayBuffer84 }85 break86 }87 case 'query':88 value = Object.fromEntries(89 Object.entries(c.req.queries()).map(([k, v]) => {90 return v.length === 1 ? [k, v[0]] : [k, v]
29 unmodified lines
modified:src/request.ts+23 added-5 removed
14 unmodified lines
15import { parse } from './utils/cookie'16import type { UnionToIntersection } from './utils/types'17import { getQueryParam, getQueryParams, decodeURIComponent_ } from './utils/url'1819type BodyType = 'json' | 'text' | 'arrayBuffer' | 'blob' | 'formData'20type BodyCache = Partial<Record<BodyType, any>>19type Body = {20 json: any21 text: string22 arrayBuffer: ArrayBuffer23 blob: Blob24 formData: FormData25}26type BodyCache = Partial<Body & { parsedBody: BodyData }>2728export class HonoRequest<P extends string = '/', I extends Input['out'] = {}> {29 raw: Request3031 private paramData: Record<string, string> | undefined32 private vData: { [K in keyof ValidationTargets]?: {} } // Short name of validatedData33 path: string28 private bodyCache: BodyCache = {}34 bodyCache: BodyCache = {}3536 constructor(37 request: Request,38 path: string = '/',
87 unmodified lines
126 }127 }128129 async parseBody<T extends BodyData = BodyData>(): Promise<T> {124 return await parseBody(this)130 if (this.bodyCache.parsedBody) return this.bodyCache.parsedBody as T131 const parsedBody = await parseBody<T>(this)132 this.bodyCache.parsedBody = parsedBody133 return parsedBody134 }135127 private cachedBody = (key: keyof BodyCache) => {136 private cachedBody = (key: keyof Body) => {137 const { bodyCache, raw } = this138 const cachedBody = bodyCache[key]139 if (cachedBody) return cachedBody140 /**141 * If an arrayBuffer cache is exist,142 * use it for creating a text, json, and others.143 */144 if (bodyCache.arrayBuffer) {145 return (async () => {146 return await new Response(bodyCache.arrayBuffer)[key]()147 })()148 }149 return (bodyCache[key] = raw[key]())150 }151152 json<T = any>(): Promise<T> {
56 unmodified lines