feat(req): cache body content (#1333)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
* feat(req): cache body content * denoify * use destruction * denoify
authored by Yusuke Wada · committed by GitHub · parent be14244 · Browse files · 7 files·+119 added−30 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
7 files+119 added−30 removed
- tests:+63 added−0 removed
- other:+56 added−30 removed
Provenance
- Commit
f254fdc- Tree
0e7ad0a- Author
Yusuke Wada <yusuke@kamawada.com>- Committer
GitHub <noreply@github.com>- Parent
be14244
7 files changed+119 added−30 removed
modified:deno_dist/utils/body.ts+3 added-1 removed
12345467891012 unmodified linesimport type { HonoRequest } from '../request.ts'
export type BodyData = Record<string, string | File>
export const parseBody = async <T extends BodyData = BodyData>( r: Request | Response r: HonoRequest | Request): Promise<T> => { let body: BodyData = {} const contentType = r.headers.get('Content-Type') if (12 unmodified linesmodified:deno_dist/validator/validator.ts+2 added-3 removed
123345639 unmodified lines464748495150515253544 unmodified lines5960616264636465666723 unmodified linesimport type { Context } from '../context.ts'import type { Env, ValidationTargets, MiddlewareHandler } from '../types.ts'import { parseBody } from '../utils/body.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.raw.clone().json() value = await c.req.json() } catch { console.error('Error: Malformed JSON in request body') return c.json( {4 unmodified lines ) } break case 'form': value = await parseBody(c.req.raw.clone()) value = await c.req.parseBody() break case 'query': value = Object.fromEntries( Object.entries(c.req.queries()).map(([k, v]) => {23 unmodified linesmodified:deno_dist/request.ts+23 added-11 removed
1+/* eslint-disable @typescript-eslint/no-explicit-any */2+/* eslint-disable @typescript-eslint/no-non-null-assertion */3 import type {4 Input,5 InputToDataByTarget,6 ParamKeys,8 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>>21+22 export class HonoRequest<P extends string = '/', I extends Input['out'] = {}> {23 raw: Request24 25 private paramData: Record<string, string> | undefined26 private vData: { [K in keyof ValidationTargets]?: {} } // Short name of validatedData27 path: string28+ private bodyCache: BodyCache = {}29 30 constructor(31 request: Request,32 path: string = '/',87 unmodified lines120 }121 }122 123 async parseBody<T extends BodyData = BodyData>(): Promise<T> {118- return await parseBody(this.raw)124+ return await parseBody(this)125 }126 121- // eslint-disable-next-line @typescript-eslint/no-explicit-any127+ private cachedBody = (key: keyof BodyCache) => {128+ const { bodyCache, raw } = this129+ const cachedBody = bodyCache[key]130+ if (cachedBody) return cachedBody131+ return (bodyCache[key] = raw[key]())132+ }133+134 json<T = any>(): Promise<T> {123- return this.raw.json()135+ return this.cachedBody('json')136 }137 126- text() {127- return this.raw.text()138+ text(): Promise<string> {139+ return this.cachedBody('text')140 }141 130- arrayBuffer() {131- return this.raw.arrayBuffer()142+ arrayBuffer(): Promise<ArrayBuffer> {143+ return this.cachedBody('arrayBuffer')144 }145 134- blob() {135- return this.raw.blob()146+ blob(): Promise<Blob> {147+ return this.cachedBody('blob')148 }149 138- formData() {139- return this.raw.formData()150+ formData(): Promise<FormData> {151+ return this.cachedBody('formData')152 }153 154 addValidatedData(target: keyof ValidationTargets, data: {}) {155 this.vData[target] = data44 unmodified linesmodified:src/utils/body.ts+3 added-1 removed
12345467891012 unmodified linesimport type { HonoRequest } from '../request'
export type BodyData = Record<string, string | File>
export const parseBody = async <T extends BodyData = BodyData>( r: Request | Response r: HonoRequest | Request): Promise<T> => { let body: BodyData = {} const contentType = r.headers.get('Content-Type') if (12 unmodified linesmodified:src/validator/validator.ts+2 added-3 removed
1 import type { Context } from '../context'2 import type { Env, ValidationTargets, MiddlewareHandler } from '../types'3-import { parseBody } from '../utils/body'3 4 type ValidationTargetKeysWithBody = 'form' | 'json'5 type ValidationTargetByMethod<M> = M extends 'get' | 'head' // GET and HEAD request must not have a body content.6 ? Exclude<keyof ValidationTargets, ValidationTargetKeysWithBody>39 unmodified lines46 47 switch (target) {48 case 'json':49 try {51- value = await c.req.raw.clone().json()50+ value = await c.req.json()51 } catch {52 console.error('Error: Malformed JSON in request body')53 return c.json(54 {4 unmodified lines59 )60 }61 break62 case 'form':64- value = await parseBody(c.req.raw.clone())63+ value = await c.req.parseBody()64 break65 case 'query':66 value = Object.fromEntries(67 Object.entries(c.req.queries()).map(([k, v]) => {23 unmodified linesmodified:src/request.test.ts+63 added
74 unmodified lines75 const foo = req.header('foo')76 expect(foo).toEqual('')77 })78 })79+80+describe('Body methods', () => {81+ test('req.text()', async () => {82+ const req = new HonoRequest(83+ new Request('http://localhost', {84+ method: 'POST',85+ body: 'foo',86+ })87+ )88+ expect(await req.text()).toBe('foo')89+ expect(await req.text()).toBe('foo') // Should be cached90+ })91+92+ test('req.json()', async () => {93+ const req = new HonoRequest(94+ new Request('http://localhost', {95+ method: 'POST',96+ body: '{"foo":"bar"}',97+ })98+ )99+ expect(await req.json()).toEqual({ foo: 'bar' })100+ expect(await req.json()).toEqual({ foo: 'bar' }) // Should be cached101+ })102+103+ test('req.arrayBuffer()', async () => {104+ const buffer = new ArrayBuffer(8)105+ const req = new HonoRequest(106+ new Request('http://localhost', {107+ method: 'POST',108+ body: buffer,109+ })110+ )111+ expect(await req.arrayBuffer()).toEqual(buffer)112+ expect(await req.arrayBuffer()).toEqual(buffer) // Should be cached113+ })114+115+ test('req.blob()', async () => {116+ const blob = new Blob(['foo'], {117+ type: 'text/plain',118+ })119+ const req = new HonoRequest(120+ new Request('http://localhost', {121+ method: 'POST',122+ body: blob,123+ })124+ )125+ expect(await req.blob()).toEqual(blob)126+ expect(await req.blob()).toEqual(blob) // Should be cached127+ })128+129+ test('req.formData()', async () => {130+ const data = new FormData()131+ data.append('foo', 'bar')132+ const req = new HonoRequest(133+ new Request('http://localhost', {134+ method: 'POST',135+ body: data,136+ })137+ )138+ expect((await req.formData()).get('foo')).toBe('bar')139+ expect((await req.formData()).get('foo')).toBe('bar') // Should be cached140+ })141+})modified:src/request.ts+23 added-11 removed
1+/* eslint-disable @typescript-eslint/no-explicit-any */2+/* eslint-disable @typescript-eslint/no-non-null-assertion */3 import type {4 Input,5 InputToDataByTarget,6 ParamKeys,8 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>>21+22 export class HonoRequest<P extends string = '/', I extends Input['out'] = {}> {23 raw: Request24 25 private paramData: Record<string, string> | undefined26 private vData: { [K in keyof ValidationTargets]?: {} } // Short name of validatedData27 path: string28+ private bodyCache: BodyCache = {}29 30 constructor(31 request: Request,32 path: string = '/',87 unmodified lines120 }121 }122 123 async parseBody<T extends BodyData = BodyData>(): Promise<T> {118- return await parseBody(this.raw)124+ return await parseBody(this)125 }126 121- // eslint-disable-next-line @typescript-eslint/no-explicit-any127+ private cachedBody = (key: keyof BodyCache) => {128+ const { bodyCache, raw } = this129+ const cachedBody = bodyCache[key]130+ if (cachedBody) return cachedBody131+ return (bodyCache[key] = raw[key]())132+ }133+134 json<T = any>(): Promise<T> {123- return this.raw.json()135+ return this.cachedBody('json')136 }137 126- text() {127- return this.raw.text()138+ text(): Promise<string> {139+ return this.cachedBody('text')140 }141 130- arrayBuffer() {131- return this.raw.arrayBuffer()142+ arrayBuffer(): Promise<ArrayBuffer> {143+ return this.cachedBody('arrayBuffer')144 }145 134- blob() {135- return this.raw.blob()146+ blob(): Promise<Blob> {147+ return this.cachedBody('blob')148 }149 138- formData() {139- return this.raw.formData()150+ formData(): Promise<FormData> {151+ return this.cachedBody('formData')152 }153 154 addValidatedData(target: keyof ValidationTargets, data: {}) {155 this.vData[target] = data44 unmodified lines