Skip to content
Myr

request.ts

This file

Path

src/request.ts

520 lines 路 14.0 KiB 路 TypeScript

Last changed by

docs(request): fix jsdoc comments for some getters (#5445)TOMIKAWA Sotarobefore adoption6d73a74

History of this file

Take 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 { getQueryParam, getQueryParams, tryDecodeURIComponent } 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}3334export class HonoRequest<P extends string = '/', I extends Input['out'] = {}> {35  /**36   * `.raw` can get the raw Request object.37   *38   * @see {@link https://hono.dev/docs/api/request#raw}39   *40   * @example41   * ```ts42   * // For Cloudflare Workers43   * app.post('/', async (c) => {44   *   const metadata = c.req.raw.cf?.hostMetadata?45   *   ...46   * })47   * ```48   */49  raw: Request5051  #validatedData: { [K in keyof ValidationTargets]?: {} } | undefined // Short name of validatedData52  #matchResult: Result<[unknown, RouterRoute]>53  routeIndex: number = 054  /**55   * `.path` can get the pathname of the request.56   *57   * @see {@link https://hono.dev/docs/api/request#path}58   *59   * @example60   * ```ts61   * app.get('/about/me', (c) => {62   *   const pathname = c.req.path // `/about/me`63   * })64   * ```65   */66  path: string67  bodyCache: BodyCache = {}6869  constructor(70    request: Request,71    path: string = '/',72    matchResult: Result<[unknown, RouterRoute]> = [[]]73  ) {74    this.raw = request75    this.path = path76    this.#matchResult = matchResult77  }7879  /**80   * `.req.param()` gets the path parameters.81   *82   * @see {@link https://hono.dev/docs/api/routing#path-parameter}83   *84   * @example85   * ```ts86   * const name = c.req.param('name')87   * // or all parameters at once88   * const { id, comment_id } = c.req.param()89   * ```90   */91  param<P2 extends ParamKeys<P> = ParamKeys<P>>(92    key: string extends P ? never : P2 extends `${infer _}?` ? never : P293  ): string94  param<P2 extends RemoveQuestion<ParamKeys<P>> = RemoveQuestion<ParamKeys<P>>>(95    key: P296  ): string | undefined97  param(key: string): string | undefined98  param<P2 extends string = P>(): Simplify<UnionToIntersection<ParamKeyToRecord<ParamKeys<P2>>>>99  param(key?: string): unknown {100    return key ? this.#getDecodedParam(key) : this.#getAllDecodedParams()101  }102103  #getDecodedParam(key: string): string | undefined {104    const paramKey = this.#matchResult[0][this.routeIndex]?.[1][key]105    const param = this.#getParamValue(paramKey)106    return param && tryDecodeURIComponent(param)107  }108109  #getAllDecodedParams(): Record<string, string> {110    const decoded: Record<string, string> = {}111112    const keys = Object.keys(this.#matchResult[0][this.routeIndex]?.[1] ?? {})113    for (const key of keys) {114      const value = this.#getParamValue(this.#matchResult[0][this.routeIndex][1][key])115      if (value !== undefined) {116        decoded[key] = tryDecodeURIComponent(value)117      }118    }119120    return decoded121  }122123  #getParamValue(paramKey: any): string | undefined {124    return this.#matchResult[1] ? this.#matchResult[1][paramKey as any] : paramKey125  }126127  /**128   * `.query()` can get querystring parameters.129   *130   * @see {@link https://hono.dev/docs/api/request#query}131   *132   * @example133   * ```ts134   * // Query params135   * app.get('/search', (c) => {136   *   const query = c.req.query('q')137   * })138   *139   * // Get all params at once140   * app.get('/search', (c) => {141   *   const { q, limit, offset } = c.req.query()142   * })143   * ```144   */145  query(key: string): string | undefined146  query(): Record<string, string>147  query(key?: string) {148    return getQueryParam(this.url, key)149  }150151  /**152   * `.queries()` can get multiple querystring parameter values, e.g. /search?tags=A&tags=B153   *154   * @see {@link https://hono.dev/docs/api/request#queries}155   *156   * @example157   * ```ts158   * app.get('/search', (c) => {159   *   // tags will be string[]160   *   const tags = c.req.queries('tags')161   * })162   * ```163   */164  queries(key: string): string[] | undefined165  queries(): Record<string, string[]>166  queries(key?: string) {167    return getQueryParams(this.url, key)168  }169170  /**171   * `.header()` can get the request header value.172   *173   * @see {@link https://hono.dev/docs/api/request#header}174   *175   * @example176   * ```ts177   * app.get('/', (c) => {178   *   const userAgent = c.req.header('User-Agent')179   * })180   * ```181   */182  header(name: RequestHeader): string | undefined183  header(name: string): string | undefined184  header(): Record<RequestHeader | (string & CustomHeader), string>185  header(name?: string) {186    if (name) {187      return this.raw.headers.get(name) ?? undefined188    }189190    const headerData: Record<string, string | undefined> = Object.create(null)191    this.raw.headers.forEach((value, key) => {192      headerData[key] = value193    })194    return headerData195  }196197  /**198   * `.parseBody()` can parse Request body of type `multipart/form-data` or `application/x-www-form-urlencoded`199   *200   * @see {@link https://hono.dev/docs/api/request#parsebody}201   *202   * @example203   * ```ts204   * app.post('/entry', async (c) => {205   *   const body = await c.req.parseBody()206   * })207   * ```208   */209  async parseBody<Options extends Partial<ParseBodyOptions>, T extends BodyData<Options>>(210    options?: Options211  ): Promise<T>212  async parseBody<T extends BodyData>(options?: Partial<ParseBodyOptions>): Promise<T>213  async parseBody(options?: Partial<ParseBodyOptions>) {214    return parseBody(this, options)215  }216217  #cachedBody = (key: keyof Body) => {218    const { bodyCache, raw } = this219    const cachedBody = bodyCache[key]220221    if (cachedBody) {222      return cachedBody223    }224225    for (const anyCachedKey in bodyCache) {226      return (bodyCache[anyCachedKey as keyof Body] as Promise<BodyInit>).then((body) => {227        if (anyCachedKey === 'json') {228          body = JSON.stringify(body)229        }230        // Rebuilding the body through a bare `Response` loses the request's media231        // type, so a representation that needs it (e.g. `formData()`) can no longer232        // be produced even though the bytes are still available. Carry the original233        // `Content-Type` over, except for `FormData`, where `Response` must generate234        // a fresh multipart boundary of its own.235        const contentType =236          anyCachedKey === 'formData' ? undefined : raw.headers.get('content-type')237        return new Response(body, {238          headers: contentType ? { 'Content-Type': contentType } : undefined,239        })[key]()240      })241    }242243    return (bodyCache[key] = raw[key]())244  }245246  /**247   * `.json()` can parse Request body of type `application/json`248   *249   * @see {@link https://hono.dev/docs/api/request#json}250   *251   * @example252   * ```ts253   * app.post('/entry', async (c) => {254   *   const body = await c.req.json()255   * })256   * ```257   */258  json<T = any>(): Promise<T> {259    return this.#cachedBody('text').then((text: string) => JSON.parse(text))260  }261262  /**263   * `.text()` can parse Request body of type `text/plain`264   *265   * @see {@link https://hono.dev/docs/api/request#text}266   *267   * @example268   * ```ts269   * app.post('/entry', async (c) => {270   *   const body = await c.req.text()271   * })272   * ```273   */274  text(): Promise<string> {275    return this.#cachedBody('text')276  }277278  /**279   * `.arrayBuffer()` parse Request body as an `ArrayBuffer`280   *281   * @see {@link https://hono.dev/docs/api/request#arraybuffer}282   *283   * @example284   * ```ts285   * app.post('/entry', async (c) => {286   *   const body = await c.req.arrayBuffer()287   * })288   * ```289   */290  arrayBuffer(): Promise<ArrayBuffer> {291    return this.#cachedBody('arrayBuffer')292  }293294  /**295   * `.bytes()` parses the request body as a `Uint8Array`.296   *297   * @see {@link https://hono.dev/docs/api/request#bytes}298   *299   * @example300   * ```ts301   * app.post('/entry', async (c) => {302   *   const body = await c.req.bytes()303   * })304   * ```305   */306  bytes(): Promise<Uint8Array> {307    return this.#cachedBody('arrayBuffer').then((buffer: ArrayBuffer) => new Uint8Array(buffer))308  }309310  /**311   * Parses the request body as a `Blob`.312   * @example313   * ```ts314   * app.post('/entry', async (c) => {315   *   const body = await c.req.blob();316   * });317   * ```318   * @see https://hono.dev/docs/api/request#blob319   */320  blob(): Promise<Blob> {321    return this.#cachedBody('blob')322  }323324  /**325   * Parses the request body as `FormData`.326   * @example327   * ```ts328   * app.post('/entry', async (c) => {329   *   const body = await c.req.formData();330   * });331   * ```332   * @see https://hono.dev/docs/api/request#formdata333   */334  formData(): Promise<FormData> {335    return this.#cachedBody('formData')336  }337338  /**339   * Adds validated data to the request.340   *341   * @param target - The target of the validation.342   * @param data - The validated data to add.343   */344  addValidatedData(target: keyof ValidationTargets, data: {}) {345    ;(this.#validatedData ??= {})[target] = data346  }347348  /**349   * Gets validated data from the request.350   *351   * @param target - The target of the validation.352   * @returns The validated data.353   *354   * @see https://hono.dev/docs/api/request#valid355   */356  valid<T extends keyof I & keyof ValidationTargets>(target: T): InputToDataByTarget<I, T>357  valid(target: keyof ValidationTargets) {358    return this.#validatedData?.[target] as unknown359  }360361  /**362   * `.url` can get the request url strings.363   *364   * @see {@link https://hono.dev/docs/api/request#url}365   *366   * @example367   * ```ts368   * app.get('/about/me', (c) => {369   *   const url = c.req.url // `http://localhost:8787/about/me`370   *   ...371   * })372   * ```373   */374  get url(): string {375    return this.raw.url376  }377378  /**379   * `.method` can get the method name of the request.380   *381   * @see {@link https://hono.dev/docs/api/request#method}382   *383   * @example384   * ```ts385   * app.get('/about/me', (c) => {386   *   const method = c.req.method // `GET`387   * })388   * ```389   */390  get method(): string {391    return this.raw.method392  }393394  get [GET_MATCH_RESULT](): Result<[unknown, RouterRoute]> {395    return this.#matchResult396  }397398  /**399   * `.matchedRoutes` can return a matched route in the handler400   *401   * @deprecated402   *403   * Use matchedRoutes helper defined in "hono/route" instead.404   *405   * @see {@link https://hono.dev/docs/api/request#matchedroutes}406   *407   * @example408   * ```ts409   * app.use('*', async function logger(c, next) {410   *   await next()411   *   c.req.matchedRoutes.forEach(({ handler, method, path }, i) => {412   *     const name = handler.name || (handler.length < 2 ? '[handler]' : '[middleware]')413   *     console.log(414   *       method,415   *       ' ',416   *       path,417   *       ' '.repeat(Math.max(10 - path.length, 0)),418   *       name,419   *       i === c.req.routeIndex ? '<- respond from here' : ''420   *     )421   *   })422   * })423   * ```424   */425  get matchedRoutes(): RouterRoute[] {426    return this.#matchResult[0].map(([[, route]]) => route)427  }428429  /**430   * `.routePath` can retrieve the path registered within the handler431   *432   * @deprecated433   *434   * Use routePath helper defined in "hono/route" instead.435   *436   * @see {@link https://hono.dev/docs/api/request#routepath}437   *438   * @example439   * ```ts440   * app.get('/posts/:id', (c) => {441   *   return c.json({ path: c.req.routePath })442   * })443   * ```444   */445  get routePath(): string {446    return this.#matchResult[0].map(([[, route]]) => route)[this.routeIndex].path447  }448}449450/**451 * Clones a HonoRequest's underlying raw Request object.452 *453 * This utility handles both consumed and unconsumed request bodies:454 * - If the request body hasn't been consumed, it uses the native `clone()` method455 * - If the request body has been consumed, it reconstructs a new Request using cached body data456 *457 * This is particularly useful when you need to:458 * - Process the same request body multiple times459 * - Pass requests to external services after validation460 *461 * @param req - The HonoRequest object to clone462 * @returns A Promise that resolves to a new Request object with the same properties463 * @throws {HTTPException} If the request body was consumed directly via `req.raw`464 *   without using HonoRequest methods (e.g., `req.json()`, `req.text()`), making it465 *   impossible to reconstruct the body from cache466 *467 * @example468 * ```ts469 * // Clone after consuming the body (e.g., after validation)470 * app.post('/forward',471 *   validator('json', (data) => data),472 *   async (c) => {473 *     const validated = c.req.valid('json')474 *     // Body has been consumed, but cloneRawRequest still works475 *     const clonedReq = await cloneRawRequest(c.req)476 *     return fetch('http://backend-service.com', clonedReq)477 *   }478 * )479 * ```480 */481export const cloneRawRequest = async (req: HonoRequest): Promise<Request> => {482  if (!req.raw.bodyUsed) {483    return req.raw.clone()484  }485486  const cacheKey = (Object.keys(req.bodyCache) as Array<keyof Body>)[0]487  if (!cacheKey) {488    throw new HTTPException(500, {489      message:490        '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.',491    })492  }493494  let body: BodyInit = await req[cacheKey]()495  const headers = req.header()496  if (cacheKey === 'json') {497    body = JSON.stringify(body)498    delete headers['content-length']499  } else if (body instanceof FormData) {500    delete headers['content-type']501    delete headers['content-length']502  }503504  const requestInit: RequiredRequestInit = {505    body,506    cache: req.raw.cache,507    credentials: req.raw.credentials,508    headers,509    integrity: req.raw.integrity,510    keepalive: req.raw.keepalive,511    method: req.method,512    mode: req.raw.mode,513    redirect: req.raw.redirect,514    referrer: req.raw.referrer,515    referrerPolicy: req.raw.referrerPolicy,516    signal: req.raw.signal,517  }518519  return new Request(req.url, requestInit)520}