request.ts
This file
Path
src/request.ts
489 lines 路 12.9 KiB 路 TypeScript
Last changed by
fix(request): remove `parseBody` from bodyCache to prevent TypeError (#4807)Yusuke Wadabefore adoption8bd9ddd
History of this fileTake it
1/* eslint-disable @typescript-eslint/no-explicit-any */2import { HTTPException } from './http-exception'3import { GET_MATCH_RESULT } from './request/constants'4import type { Result } from './router'5import type {6 Input,7 InputToDataByTarget,8 ParamKeyToRecord,9 ParamKeys,10 RemoveQuestion,11 RouterRoute,12 ValidationTargets,13} from './types'14import { parseBody } from './utils/body'15import type { BodyData, ParseBodyOptions } from './utils/body'16import type { CustomHeader, RequestHeader } from './utils/headers'17import type { Simplify, UnionToIntersection } from './utils/types'18import { decodeURIComponent_, getQueryParam, getQueryParams, tryDecode } from './utils/url'1920type Body = {21 json: any22 text: string23 arrayBuffer: ArrayBuffer24 blob: Blob25 formData: FormData26}27type BodyCache = Partial<Body>2829type OptionalRequestInitProperties = 'window' | 'priority'30type RequiredRequestInit = Required<Omit<RequestInit, OptionalRequestInitProperties>> & {31 [Key in OptionalRequestInitProperties]?: RequestInit[Key]32}3334const tryDecodeURIComponent = (str: string) => tryDecode(str, decodeURIComponent_)3536export class HonoRequest<P extends string = '/', I extends Input['out'] = {}> {37 /**38 * `.raw` can get the raw Request object.39 *40 * @see {@link https://hono.dev/docs/api/request#raw}41 *42 * @example43 * ```ts44 * // For Cloudflare Workers45 * app.post('/', async (c) => {46 * const metadata = c.req.raw.cf?.hostMetadata?47 * ...48 * })49 * ```50 */51 raw: Request5253 #validatedData: { [K in keyof ValidationTargets]?: {} } // Short name of validatedData54 #matchResult: Result<[unknown, RouterRoute]>55 routeIndex: number = 056 /**57 * `.path` can get the pathname of the request.58 *59 * @see {@link https://hono.dev/docs/api/request#path}60 *61 * @example62 * ```ts63 * app.get('/about/me', (c) => {64 * const pathname = c.req.path // `/about/me`65 * })66 * ```67 */68 path: string69 bodyCache: BodyCache = {}7071 constructor(72 request: Request,73 path: string = '/',74 matchResult: Result<[unknown, RouterRoute]> = [[]]75 ) {76 this.raw = request77 this.path = path78 this.#matchResult = matchResult79 this.#validatedData = {}80 }8182 /**83 * `.req.param()` gets the path parameters.84 *85 * @see {@link https://hono.dev/docs/api/routing#path-parameter}86 *87 * @example88 * ```ts89 * const name = c.req.param('name')90 * // or all parameters at once91 * const { id, comment_id } = c.req.param()92 * ```93 */94 param<P2 extends ParamKeys<P> = ParamKeys<P>>(95 key: string extends P ? never : P2 extends `${infer _}?` ? never : P296 ): string97 param<P2 extends RemoveQuestion<ParamKeys<P>> = RemoveQuestion<ParamKeys<P>>>(98 key: P299 ): string | undefined100 param(key: string): string | undefined101 param<P2 extends string = P>(): Simplify<UnionToIntersection<ParamKeyToRecord<ParamKeys<P2>>>>102 param(key?: string): unknown {103 return key ? this.#getDecodedParam(key) : this.#getAllDecodedParams()104 }105106 #getDecodedParam(key: string): string | undefined {107 const paramKey = this.#matchResult[0][this.routeIndex][1][key]108 const param = this.#getParamValue(paramKey)109 return param && /\%/.test(param) ? tryDecodeURIComponent(param) : param110 }111112 #getAllDecodedParams(): Record<string, string> {113 const decoded: Record<string, string> = {}114115 const keys = Object.keys(this.#matchResult[0][this.routeIndex][1])116 for (const key of keys) {117 const value = this.#getParamValue(this.#matchResult[0][this.routeIndex][1][key])118 if (value !== undefined) {119 decoded[key] = /\%/.test(value) ? tryDecodeURIComponent(value) : value120 }121 }122123 return decoded124 }125126 #getParamValue(paramKey: any): string | undefined {127 return this.#matchResult[1] ? this.#matchResult[1][paramKey as any] : paramKey128 }129130 /**131 * `.query()` can get querystring parameters.132 *133 * @see {@link https://hono.dev/docs/api/request#query}134 *135 * @example136 * ```ts137 * // Query params138 * app.get('/search', (c) => {139 * const query = c.req.query('q')140 * })141 *142 * // Get all params at once143 * app.get('/search', (c) => {144 * const { q, limit, offset } = c.req.query()145 * })146 * ```147 */148 query(key: string): string | undefined149 query(): Record<string, string>150 query(key?: string) {151 return getQueryParam(this.url, key)152 }153154 /**155 * `.queries()` can get multiple querystring parameter values, e.g. /search?tags=A&tags=B156 *157 * @see {@link https://hono.dev/docs/api/request#queries}158 *159 * @example160 * ```ts161 * app.get('/search', (c) => {162 * // tags will be string[]163 * const tags = c.req.queries('tags')164 * })165 * ```166 */167 queries(key: string): string[] | undefined168 queries(): Record<string, string[]>169 queries(key?: string) {170 return getQueryParams(this.url, key)171 }172173 /**174 * `.header()` can get the request header value.175 *176 * @see {@link https://hono.dev/docs/api/request#header}177 *178 * @example179 * ```ts180 * app.get('/', (c) => {181 * const userAgent = c.req.header('User-Agent')182 * })183 * ```184 */185 header(name: RequestHeader): string | undefined186 header(name: string): string | undefined187 header(): Record<RequestHeader | (string & CustomHeader), string>188 header(name?: string) {189 if (name) {190 return this.raw.headers.get(name) ?? undefined191 }192193 const headerData: Record<string, string | undefined> = {}194 this.raw.headers.forEach((value, key) => {195 headerData[key] = value196 })197 return headerData198 }199200 /**201 * `.parseBody()` can parse Request body of type `multipart/form-data` or `application/x-www-form-urlencoded`202 *203 * @see {@link https://hono.dev/docs/api/request#parsebody}204 *205 * @example206 * ```ts207 * app.post('/entry', async (c) => {208 * const body = await c.req.parseBody()209 * })210 * ```211 */212 async parseBody<Options extends Partial<ParseBodyOptions>, T extends BodyData<Options>>(213 options?: Options214 ): Promise<T>215 async parseBody<T extends BodyData>(options?: Partial<ParseBodyOptions>): Promise<T>216 async parseBody(options?: Partial<ParseBodyOptions>) {217 return parseBody(this, options)218 }219220 #cachedBody = (key: keyof Body) => {221 const { bodyCache, raw } = this222 const cachedBody = bodyCache[key]223224 if (cachedBody) {225 return cachedBody226 }227228 const anyCachedKey = Object.keys(bodyCache)[0]229 if (anyCachedKey) {230 return (bodyCache[anyCachedKey as keyof Body] as Promise<BodyInit>).then((body) => {231 if (anyCachedKey === 'json') {232 body = JSON.stringify(body)233 }234 return new Response(body)[key]()235 })236 }237238 return (bodyCache[key] = raw[key]())239 }240241 /**242 * `.json()` can parse Request body of type `application/json`243 *244 * @see {@link https://hono.dev/docs/api/request#json}245 *246 * @example247 * ```ts248 * app.post('/entry', async (c) => {249 * const body = await c.req.json()250 * })251 * ```252 */253 json<T = any>(): Promise<T> {254 return this.#cachedBody('text').then((text: string) => JSON.parse(text))255 }256257 /**258 * `.text()` can parse Request body of type `text/plain`259 *260 * @see {@link https://hono.dev/docs/api/request#text}261 *262 * @example263 * ```ts264 * app.post('/entry', async (c) => {265 * const body = await c.req.text()266 * })267 * ```268 */269 text(): Promise<string> {270 return this.#cachedBody('text')271 }272273 /**274 * `.arrayBuffer()` parse Request body as an `ArrayBuffer`275 *276 * @see {@link https://hono.dev/docs/api/request#arraybuffer}277 *278 * @example279 * ```ts280 * app.post('/entry', async (c) => {281 * const body = await c.req.arrayBuffer()282 * })283 * ```284 */285 arrayBuffer(): Promise<ArrayBuffer> {286 return this.#cachedBody('arrayBuffer')287 }288289 /**290 * Parses the request body as a `Blob`.291 * @example292 * ```ts293 * app.post('/entry', async (c) => {294 * const body = await c.req.blob();295 * });296 * ```297 * @see https://hono.dev/docs/api/request#blob298 */299 blob(): Promise<Blob> {300 return this.#cachedBody('blob')301 }302303 /**304 * Parses the request body as `FormData`.305 * @example306 * ```ts307 * app.post('/entry', async (c) => {308 * const body = await c.req.formData();309 * });310 * ```311 * @see https://hono.dev/docs/api/request#formdata312 */313 formData(): Promise<FormData> {314 return this.#cachedBody('formData')315 }316317 /**318 * Adds validated data to the request.319 *320 * @param target - The target of the validation.321 * @param data - The validated data to add.322 */323 addValidatedData(target: keyof ValidationTargets, data: {}) {324 this.#validatedData[target] = data325 }326327 /**328 * Gets validated data from the request.329 *330 * @param target - The target of the validation.331 * @returns The validated data.332 *333 * @see https://hono.dev/docs/api/request#valid334 */335 valid<T extends keyof I & keyof ValidationTargets>(target: T): InputToDataByTarget<I, T>336 valid(target: keyof ValidationTargets) {337 return this.#validatedData[target] as unknown338 }339340 /**341 * `.url()` can get the request url strings.342 *343 * @see {@link https://hono.dev/docs/api/request#url}344 *345 * @example346 * ```ts347 * app.get('/about/me', (c) => {348 * const url = c.req.url // `http://localhost:8787/about/me`349 * ...350 * })351 * ```352 */353 get url(): string {354 return this.raw.url355 }356357 /**358 * `.method()` can get the method name of the request.359 *360 * @see {@link https://hono.dev/docs/api/request#method}361 *362 * @example363 * ```ts364 * app.get('/about/me', (c) => {365 * const method = c.req.method // `GET`366 * })367 * ```368 */369 get method(): string {370 return this.raw.method371 }372373 get [GET_MATCH_RESULT](): Result<[unknown, RouterRoute]> {374 return this.#matchResult375 }376377 /**378 * `.matchedRoutes()` can return a matched route in the handler379 *380 * @deprecated381 *382 * Use matchedRoutes helper defined in "hono/route" instead.383 *384 * @see {@link https://hono.dev/docs/api/request#matchedroutes}385 *386 * @example387 * ```ts388 * app.use('*', async function logger(c, next) {389 * await next()390 * c.req.matchedRoutes.forEach(({ handler, method, path }, i) => {391 * const name = handler.name || (handler.length < 2 ? '[handler]' : '[middleware]')392 * console.log(393 * method,394 * ' ',395 * path,396 * ' '.repeat(Math.max(10 - path.length, 0)),397 * name,398 * i === c.req.routeIndex ? '<- respond from here' : ''399 * )400 * })401 * })402 * ```403 */404 get matchedRoutes(): RouterRoute[] {405 return this.#matchResult[0].map(([[, route]]) => route)406 }407408 /**409 * `routePath()` can retrieve the path registered within the handler410 *411 * @deprecated412 *413 * Use routePath helper defined in "hono/route" instead.414 *415 * @see {@link https://hono.dev/docs/api/request#routepath}416 *417 * @example418 * ```ts419 * app.get('/posts/:id', (c) => {420 * return c.json({ path: c.req.routePath })421 * })422 * ```423 */424 get routePath(): string {425 return this.#matchResult[0].map(([[, route]]) => route)[this.routeIndex].path426 }427}428429/**430 * Clones a HonoRequest's underlying raw Request object.431 *432 * This utility handles both consumed and unconsumed request bodies:433 * - If the request body hasn't been consumed, it uses the native `clone()` method434 * - If the request body has been consumed, it reconstructs a new Request using cached body data435 *436 * This is particularly useful when you need to:437 * - Process the same request body multiple times438 * - Pass requests to external services after validation439 *440 * @param req - The HonoRequest object to clone441 * @returns A Promise that resolves to a new Request object with the same properties442 * @throws {HTTPException} If the request body was consumed directly via `req.raw`443 * without using HonoRequest methods (e.g., `req.json()`, `req.text()`), making it444 * impossible to reconstruct the body from cache445 *446 * @example447 * ```ts448 * // Clone after consuming the body (e.g., after validation)449 * app.post('/forward',450 * validator('json', (data) => data),451 * async (c) => {452 * const validated = c.req.valid('json')453 * // Body has been consumed, but cloneRawRequest still works454 * const clonedReq = await cloneRawRequest(c.req)455 * return fetch('http://backend-service.com', clonedReq)456 * }457 * )458 * ```459 */460export const cloneRawRequest = async (req: HonoRequest): Promise<Request> => {461 if (!req.raw.bodyUsed) {462 return req.raw.clone()463 }464465 const cacheKey = (Object.keys(req.bodyCache) as Array<keyof Body>)[0]466 if (!cacheKey) {467 throw new HTTPException(500, {468 message:469 'Cannot clone request: body was already consumed and not cached. Please use HonoRequest methods (e.g., req.json(), req.text()) instead of consuming req.raw directly.',470 })471 }472473 const requestInit: RequiredRequestInit = {474 body: await req[cacheKey](),475 cache: req.raw.cache,476 credentials: req.raw.credentials,477 headers: req.header(),478 integrity: req.raw.integrity,479 keepalive: req.raw.keepalive,480 method: req.method,481 mode: req.raw.mode,482 redirect: req.raw.redirect,483 referrer: req.raw.referrer,484 referrerPolicy: req.raw.referrerPolicy,485 signal: req.raw.signal,486 }487488 return new Request(req.url, requestInit)489}