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
Provenance
- Commit
5cbd89c- Tree
138d1c3- Author
Yusuke Wada <yusuke@kamawada.com>- Committer
GitHub <noreply@github.com>- Parent
0316bba
10 files changed+217 added−33 removed
modified:deno_dist/utils/body.ts+11 added-7 removed
1234566789910111213141516171516171819181920212223242526import type { HonoRequest } from '../request.ts'
export type BodyData = Record<string, string | File>
export const parseBody = async <T extends BodyData = BodyData>( r: HonoRequest | Request request: HonoRequest | Request): Promise<T> => { let body: BodyData = {} const contentType = r.headers.get('Content-Type') const contentType = request.headers.get('Content-Type')
if ( contentType && (contentType.startsWith('multipart/form-data') || contentType.startsWith('application/x-www-form-urlencoded')) ) { const formData = await request.formData() if (formData) { const form: BodyData = {} ;(await r.formData()).forEach((value, key) => { form[key] = value }) body = form const form: BodyData = {} formData.forEach((value, key) => { form[key] = value }) body = form } } return body as T}modified:deno_dist/utils/buffer.ts+31 added
45 unmodified lines464748495051525354555657585960616263646566676869707172737475767778798045 unmodified lines return enc.decode(buffer) } return buffer}
const _decodeURIComponent = decodeURIComponent
export const bufferToFormData = (arrayBuffer: ArrayBuffer, contentType: string) => { const decoder = new TextDecoder('utf-8') const content = decoder.decode(arrayBuffer) const formData = new FormData()
const boundaryMatch = contentType.match(/boundary=(.+)/) const boundary = boundaryMatch ? boundaryMatch[1] : ''
if (contentType.startsWith('multipart/form-data') && boundary) { const parts = content.split('--' + boundary).slice(1, -1) for (const part of parts) { const [header, body] = part.split('\r\n\r\n') const nameMatch = header.match(/name="([^"]+)"/) if (nameMatch) { const name = nameMatch[1] formData.append(name, body.trim()) } } } else if (contentType.startsWith('application/x-www-form-urlencoded')) { const pairs = content.split('&') for (const pair of pairs) { const [key, value] = pair.split('=') formData.append(_decodeURIComponent(key), _decodeURIComponent(value)) } }
return formData}modified:deno_dist/validator/validator.ts+24 added-3 removed
12345678939 unmodified lines49505152515354555657585960616263643 unmodified lines6869707163647273747576777879808182838485868788899029 unmodified linesimport type { Context } from '../context.ts'import { getCookie } from '../helper/cookie/index.ts'import type { Env, ValidationTargets, MiddlewareHandler } from '../types.ts'import type { BodyData } from '../utils/body.ts'import { bufferToFormData } from '../utils/buffer.ts'
type ValidationTargetKeysWithBody = 'form' | 'json'type ValidationTargetByMethod<M> = M extends 'get' | 'head' // GET and HEAD request must not have a body content. ? Exclude<keyof ValidationTargets, ValidationTargetKeysWithBody>39 unmodified lines
switch (target) { case 'json': try { value = await c.req.json() /** * Get the arrayBuffer first, create JSON object via Response, * and cache the arrayBuffer in the c.req.bodyCache. */ const arrayBuffer = c.req.bodyCache.arrayBuffer ?? (await c.req.raw.arrayBuffer()) value = await new Response(arrayBuffer).json() c.req.bodyCache.json = value c.req.bodyCache.arrayBuffer = arrayBuffer } catch { console.error('Error: Malformed JSON in request body') return c.json( {3 unmodified lines 400 ) } break case 'form': value = await c.req.parseBody() case 'form': { const contentType = c.req.header('Content-Type') if (contentType) { const arrayBuffer = c.req.bodyCache.arrayBuffer ?? (await c.req.raw.arrayBuffer()) const formData = bufferToFormData(arrayBuffer, contentType) const form: BodyData = {} formData.forEach((value, key) => { form[key] = value }) value = form c.req.bodyCache.formData = formData c.req.bodyCache.arrayBuffer = arrayBuffer } break } case 'query': value = Object.fromEntries( Object.entries(c.req.queries()).map(([k, v]) => { return v.length === 1 ? [k, v[0]] : [k, v]29 unmodified linesmodified:deno_dist/request.ts+23 added-5 removed
14 unmodified lines15 import { parse } from './utils/cookie.ts'16 import type { UnionToIntersection } from './utils/types.ts'17 import { getQueryParam, getQueryParams, decodeURIComponent_ } from './utils/url.ts'18 19-type BodyType = 'json' | 'text' | 'arrayBuffer' | 'blob' | 'formData'20-type BodyCache = Partial<Record<BodyType, any>>19+type Body = {20+ json: any21+ text: string22+ arrayBuffer: ArrayBuffer23+ blob: Blob24+ formData: FormData25+}26+type BodyCache = Partial<Body & { parsedBody: BodyData }>27 28 export class HonoRequest<P extends string = '/', I extends Input['out'] = {}> {29 raw: Request30 31 private paramData: Record<string, string> | undefined32 private vData: { [K in keyof ValidationTargets]?: {} } // Short name of validatedData33 path: string28- private bodyCache: BodyCache = {}34+ bodyCache: BodyCache = {}35 36 constructor(37 request: Request,38 path: string = '/',87 unmodified lines126 }127 }128 129 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 }135 127- 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 }151 152 json<T = any>(): Promise<T> {56 unmodified linesmodified:src/utils/body.ts+11 added-7 removed
1 unmodified line2 3 export type BodyData = Record<string, string | File>4 5 export 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')10+11 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
1 import { SHA256 as sha256CryptoJS } from 'crypto-js'2-import { timingSafeEqual, bufferToString } from './buffer'2+import { timingSafeEqual, bufferToString, bufferToFormData } from './buffer'3 4 describe('buffer', () => {5 it('positive', async () => {6 expect(45 unmodified lines52 const buffer = Uint8Array.from(bytes).buffer53 expect(bufferToString(buffer)).toBe('あいうえお')54 })55 })56+57+describe('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).buffer63+64+ const result = bufferToFormData(arrayBuffer, 'multipart/form-data; boundary=sampleboundary')65+66+ expect(result.get('test')).toBe('Hello')67+ })68+69+ 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).buffer73+74+ const result = bufferToFormData(arrayBuffer, 'application/x-www-form-urlencoded')75+76+ expect(result.get('key1')).toBe('value1')77+ expect(result.get('key2')).toBe('value2')78+ })79+})modified:src/utils/buffer.ts+31 added
45 unmodified lines46 return enc.decode(buffer)47 }48 return buffer49 }50+51+const _decodeURIComponent = decodeURIComponent52+53+export const bufferToFormData = (arrayBuffer: ArrayBuffer, contentType: string) => {54+ const decoder = new TextDecoder('utf-8')55+ const content = decoder.decode(arrayBuffer)56+ const formData = new FormData()57+58+ const boundaryMatch = contentType.match(/boundary=(.+)/)59+ const boundary = boundaryMatch ? boundaryMatch[1] : ''60+61+ 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+ }78+79+ return formData80+}modified:src/validator/validator.test.ts+14 added-2 removed
658 unmodified lines659 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 lines691 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 linesmodified:src/validator/validator.ts+24 added-3 removed
1 import type { Context } from '../context'2 import { getCookie } from '../helper/cookie'3 import type { Env, ValidationTargets, MiddlewareHandler } from '../types'4+import type { BodyData } from '../utils/body'5+import { bufferToFormData } from '../utils/buffer'6 7 type ValidationTargetKeysWithBody = 'form' | 'json'8 type ValidationTargetByMethod<M> = M extends 'get' | 'head' // GET and HEAD request must not have a body content.9 ? Exclude<keyof ValidationTargets, ValidationTargetKeysWithBody>39 unmodified lines49 50 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 lines68 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 linesmodified:src/request.ts+23 added-5 removed
14 unmodified lines15 import { parse } from './utils/cookie'16 import type { UnionToIntersection } from './utils/types'17 import { getQueryParam, getQueryParams, decodeURIComponent_ } from './utils/url'18 19-type BodyType = 'json' | 'text' | 'arrayBuffer' | 'blob' | 'formData'20-type BodyCache = Partial<Record<BodyType, any>>19+type Body = {20+ json: any21+ text: string22+ arrayBuffer: ArrayBuffer23+ blob: Blob24+ formData: FormData25+}26+type BodyCache = Partial<Body & { parsedBody: BodyData }>27 28 export class HonoRequest<P extends string = '/', I extends Input['out'] = {}> {29 raw: Request30 31 private paramData: Record<string, string> | undefined32 private vData: { [K in keyof ValidationTargets]?: {} } // Short name of validatedData33 path: string28- private bodyCache: BodyCache = {}34+ bodyCache: BodyCache = {}35 36 constructor(37 request: Request,38 path: string = '/',87 unmodified lines126 }127 }128 129 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 }135 127- 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 }151 152 json<T = any>(): Promise<T> {56 unmodified lines