Skip to content
Myr

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

7 files+119 added−30 removed

modified:deno_dist/utils/body.ts+3 added-1 removed
modified:deno_dist/validator/validator.ts+2 added-3 removed
modified: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 */3import type {4 Input,5 InputToDataByTarget,6 ParamKeys,
8 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>>2122export class HonoRequest<P extends string = '/', I extends Input['out'] = {}> {23 raw: Request2425 private paramData: Record<string, string> | undefined26 private vData: { [K in keyof ValidationTargets]?: {} } // Short name of validatedData27 path: string28 private bodyCache: BodyCache = {}2930 constructor(31 request: Request,32 path: string = '/',
87 unmodified lines
120 }121 }122123 async parseBody<T extends BodyData = BodyData>(): Promise<T> {118 return await parseBody(this.raw)124 return await parseBody(this)125 }126121 // 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 }133134 json<T = any>(): Promise<T> {123 return this.raw.json()135 return this.cachedBody('json')136 }137126 text() {127 return this.raw.text()138 text(): Promise<string> {139 return this.cachedBody('text')140 }141130 arrayBuffer() {131 return this.raw.arrayBuffer()142 arrayBuffer(): Promise<ArrayBuffer> {143 return this.cachedBody('arrayBuffer')144 }145134 blob() {135 return this.raw.blob()146 blob(): Promise<Blob> {147 return this.cachedBody('blob')148 }149138 formData() {139 return this.raw.formData()150 formData(): Promise<FormData> {151 return this.cachedBody('formData')152 }153154 addValidatedData(target: keyof ValidationTargets, data: {}) {155 this.vData[target] = data
44 unmodified lines
modified:src/utils/body.ts+3 added-1 removed
modified:src/validator/validator.ts+2 added-3 removed
1import type { Context } from '../context'2import type { Env, ValidationTargets, MiddlewareHandler } from '../types'3import { parseBody } from '../utils/body'34type ValidationTargetKeysWithBody = 'form' | 'json'5type ValidationTargetByMethod<M> = M extends 'get' | 'head' // GET and HEAD request must not have a body content.6 ? Exclude<keyof ValidationTargets, ValidationTargetKeysWithBody>
39 unmodified lines
4647 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 lines
59 )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 lines
modified:src/request.test.ts+63 added
74 unmodified lines
75 const foo = req.header('foo')76 expect(foo).toEqual('')77 })78})7980describe('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 })9192 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 })102103 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 })114115 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 })128129 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 */3import type {4 Input,5 InputToDataByTarget,6 ParamKeys,
8 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>>2122export class HonoRequest<P extends string = '/', I extends Input['out'] = {}> {23 raw: Request2425 private paramData: Record<string, string> | undefined26 private vData: { [K in keyof ValidationTargets]?: {} } // Short name of validatedData27 path: string28 private bodyCache: BodyCache = {}2930 constructor(31 request: Request,32 path: string = '/',
87 unmodified lines
120 }121 }122123 async parseBody<T extends BodyData = BodyData>(): Promise<T> {118 return await parseBody(this.raw)124 return await parseBody(this)125 }126121 // 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 }133134 json<T = any>(): Promise<T> {123 return this.raw.json()135 return this.cachedBody('json')136 }137126 text() {127 return this.raw.text()138 text(): Promise<string> {139 return this.cachedBody('text')140 }141130 arrayBuffer() {131 return this.raw.arrayBuffer()142 arrayBuffer(): Promise<ArrayBuffer> {143 return this.cachedBody('arrayBuffer')144 }145134 blob() {135 return this.raw.blob()146 blob(): Promise<Blob> {147 return this.cachedBody('blob')148 }149138 formData() {139 return this.raw.formData()150 formData(): Promise<FormData> {151 return this.cachedBody('formData')152 }153154 addValidatedData(target: keyof ValidationTargets, data: {}) {155 this.vData[target] = data
44 unmodified lines