Skip to content
Myr

request.ts

This file

Path

src/request.ts

406 lines 路 10.3 KiB 路 TypeScript

Last changed by

refactor(request): `toLowerCase()` is unnecessary for `req.header()` (#3880)Yusuke Wadabefore adoption65edaf2

History of this file

Take it

1/* eslint-disable @typescript-eslint/no-explicit-any */2import type { Result } from './router'3import type {4  Input,5  InputToDataByTarget,6  ParamKeyToRecord,7  ParamKeys,8  RemoveQuestion,9  RouterRoute,10  ValidationTargets,11} from './types'12import { parseBody } from './utils/body'13import type { BodyData, ParseBodyOptions } from './utils/body'14import type { CustomHeader, RequestHeader } from './utils/headers'15import type { Simplify, UnionToIntersection } from './utils/types'16import { decodeURIComponent_, getQueryParam, getQueryParams, tryDecode } from './utils/url'1718type Body = {19  json: any20  text: string21  arrayBuffer: ArrayBuffer22  blob: Blob23  formData: FormData24}25type BodyCache = Partial<Body & { parsedBody: BodyData }>2627const tryDecodeURIComponent = (str: string) => tryDecode(str, decodeURIComponent_)2829export class HonoRequest<P extends string = '/', I extends Input['out'] = {}> {30  /**31   * `.raw` can get the raw Request object.32   *33   * @see {@link https://hono.dev/docs/api/request#raw}34   *35   * @example36   * ```ts37   * // For Cloudflare Workers38   * app.post('/', async (c) => {39   *   const metadata = c.req.raw.cf?.hostMetadata?40   *   ...41   * })42   * ```43   */44  raw: Request4546  #validatedData: { [K in keyof ValidationTargets]?: {} } // Short name of validatedData47  #matchResult: Result<[unknown, RouterRoute]>48  routeIndex: number = 049  /**50   * `.path` can get the pathname of the request.51   *52   * @see {@link https://hono.dev/docs/api/request#path}53   *54   * @example55   * ```ts56   * app.get('/about/me', (c) => {57   *   const pathname = c.req.path // `/about/me`58   * })59   * ```60   */61  path: string62  bodyCache: BodyCache = {}6364  constructor(65    request: Request,66    path: string = '/',67    matchResult: Result<[unknown, RouterRoute]> = [[]]68  ) {69    this.raw = request70    this.path = path71    this.#matchResult = matchResult72    this.#validatedData = {}73  }7475  /**76   * `.req.param()` gets the path parameters.77   *78   * @see {@link https://hono.dev/docs/api/routing#path-parameter}79   *80   * @example81   * ```ts82   * const name = c.req.param('name')83   * // or all parameters at once84   * const { id, comment_id } = c.req.param()85   * ```86   */87  param<P2 extends ParamKeys<P> = ParamKeys<P>>(key: P2 extends `${infer _}?` ? never : P2): string88  param<P2 extends RemoveQuestion<ParamKeys<P>> = RemoveQuestion<ParamKeys<P>>>(89    key: P290  ): string | undefined91  param(key: string): string | undefined92  param<P2 extends string = P>(): Simplify<UnionToIntersection<ParamKeyToRecord<ParamKeys<P2>>>>93  param(key?: string): unknown {94    return key ? this.#getDecodedParam(key) : this.#getAllDecodedParams()95  }9697  #getDecodedParam(key: string): string | undefined {98    const paramKey = this.#matchResult[0][this.routeIndex][1][key]99    const param = this.#getParamValue(paramKey)100    return param ? (/\%/.test(param) ? tryDecodeURIComponent(param) : param) : undefined101  }102103  #getAllDecodedParams(): Record<string, string> {104    const decoded: Record<string, string> = {}105106    const keys = Object.keys(this.#matchResult[0][this.routeIndex][1])107    for (const key of keys) {108      const value = this.#getParamValue(this.#matchResult[0][this.routeIndex][1][key])109      if (value && typeof value === 'string') {110        decoded[key] = /\%/.test(value) ? tryDecodeURIComponent(value) : value111      }112    }113114    return decoded115  }116117  #getParamValue(paramKey: any): string | undefined {118    return this.#matchResult[1] ? this.#matchResult[1][paramKey as any] : paramKey119  }120121  /**122   * `.query()` can get querystring parameters.123   *124   * @see {@link https://hono.dev/docs/api/request#query}125   *126   * @example127   * ```ts128   * // Query params129   * app.get('/search', (c) => {130   *   const query = c.req.query('q')131   * })132   *133   * // Get all params at once134   * app.get('/search', (c) => {135   *   const { q, limit, offset } = c.req.query()136   * })137   * ```138   */139  query(key: string): string | undefined140  query(): Record<string, string>141  query(key?: string) {142    return getQueryParam(this.url, key)143  }144145  /**146   * `.queries()` can get multiple querystring parameter values, e.g. /search?tags=A&tags=B147   *148   * @see {@link https://hono.dev/docs/api/request#queries}149   *150   * @example151   * ```ts152   * app.get('/search', (c) => {153   *   // tags will be string[]154   *   const tags = c.req.queries('tags')155   * })156   * ```157   */158  queries(key: string): string[] | undefined159  queries(): Record<string, string[]>160  queries(key?: string) {161    return getQueryParams(this.url, key)162  }163164  /**165   * `.header()` can get the request header value.166   *167   * @see {@link https://hono.dev/docs/api/request#header}168   *169   * @example170   * ```ts171   * app.get('/', (c) => {172   *   const userAgent = c.req.header('User-Agent')173   * })174   * ```175   */176  header(name: RequestHeader): string | undefined177  header(name: string): string | undefined178  header(): Record<RequestHeader | (string & CustomHeader), string>179  header(name?: string) {180    if (name) {181      return this.raw.headers.get(name) ?? undefined182    }183184    const headerData: Record<string, string | undefined> = {}185    this.raw.headers.forEach((value, key) => {186      headerData[key] = value187    })188    return headerData189  }190191  /**192   * `.parseBody()` can parse Request body of type `multipart/form-data` or `application/x-www-form-urlencoded`193   *194   * @see {@link https://hono.dev/docs/api/request#parsebody}195   *196   * @example197   * ```ts198   * app.post('/entry', async (c) => {199   *   const body = await c.req.parseBody()200   * })201   * ```202   */203  async parseBody<Options extends Partial<ParseBodyOptions>, T extends BodyData<Options>>(204    options?: Options205  ): Promise<T>206  async parseBody<T extends BodyData>(options?: Partial<ParseBodyOptions>): Promise<T>207  async parseBody(options?: Partial<ParseBodyOptions>) {208    return (this.bodyCache.parsedBody ??= await parseBody(this, options))209  }210211  #cachedBody = (key: keyof Body) => {212    const { bodyCache, raw } = this213    const cachedBody = bodyCache[key]214215    if (cachedBody) {216      return cachedBody217    }218219    const anyCachedKey = Object.keys(bodyCache)[0]220    if (anyCachedKey) {221      return (bodyCache[anyCachedKey as keyof Body] as Promise<BodyInit>).then((body) => {222        if (anyCachedKey === 'json') {223          body = JSON.stringify(body)224        }225        return new Response(body)[key]()226      })227    }228229    return (bodyCache[key] = raw[key]())230  }231232  /**233   * `.json()` can parse Request body of type `application/json`234   *235   * @see {@link https://hono.dev/docs/api/request#json}236   *237   * @example238   * ```ts239   * app.post('/entry', async (c) => {240   *   const body = await c.req.json()241   * })242   * ```243   */244  json<T = any>(): Promise<T> {245    return this.#cachedBody('json')246  }247248  /**249   * `.text()` can parse Request body of type `text/plain`250   *251   * @see {@link https://hono.dev/docs/api/request#text}252   *253   * @example254   * ```ts255   * app.post('/entry', async (c) => {256   *   const body = await c.req.text()257   * })258   * ```259   */260  text(): Promise<string> {261    return this.#cachedBody('text')262  }263264  /**265   * `.arrayBuffer()` parse Request body as an `ArrayBuffer`266   *267   * @see {@link https://hono.dev/docs/api/request#arraybuffer}268   *269   * @example270   * ```ts271   * app.post('/entry', async (c) => {272   *   const body = await c.req.arrayBuffer()273   * })274   * ```275   */276  arrayBuffer(): Promise<ArrayBuffer> {277    return this.#cachedBody('arrayBuffer')278  }279280  /**281   * Parses the request body as a `Blob`.282   * @example283   * ```ts284   * app.post('/entry', async (c) => {285   *   const body = await c.req.blob();286   * });287   * ```288   * @see https://hono.dev/docs/api/request#blob289   */290  blob(): Promise<Blob> {291    return this.#cachedBody('blob')292  }293294  /**295   * Parses the request body as `FormData`.296   * @example297   * ```ts298   * app.post('/entry', async (c) => {299   *   const body = await c.req.formData();300   * });301   * ```302   * @see https://hono.dev/docs/api/request#formdata303   */304  formData(): Promise<FormData> {305    return this.#cachedBody('formData')306  }307308  /**309   * Adds validated data to the request.310   *311   * @param target - The target of the validation.312   * @param data - The validated data to add.313   */314  addValidatedData(target: keyof ValidationTargets, data: {}) {315    this.#validatedData[target] = data316  }317318  /**319   * Gets validated data from the request.320   *321   * @param target - The target of the validation.322   * @returns The validated data.323   *324   * @see https://hono.dev/docs/api/request#valid325   */326  valid<T extends keyof I & keyof ValidationTargets>(target: T): InputToDataByTarget<I, T>327  valid(target: keyof ValidationTargets) {328    return this.#validatedData[target] as unknown329  }330331  /**332   * `.url()` can get the request url strings.333   *334   * @see {@link https://hono.dev/docs/api/request#url}335   *336   * @example337   * ```ts338   * app.get('/about/me', (c) => {339   *   const url = c.req.url // `http://localhost:8787/about/me`340   *   ...341   * })342   * ```343   */344  get url(): string {345    return this.raw.url346  }347348  /**349   * `.method()` can get the method name of the request.350   *351   * @see {@link https://hono.dev/docs/api/request#method}352   *353   * @example354   * ```ts355   * app.get('/about/me', (c) => {356   *   const method = c.req.method // `GET`357   * })358   * ```359   */360  get method(): string {361    return this.raw.method362  }363364  /**365   * `.matchedRoutes()` can return a matched route in the handler366   *367   * @see {@link https://hono.dev/docs/api/request#matchedroutes}368   *369   * @example370   * ```ts371   * app.use('*', async function logger(c, next) {372   *   await next()373   *   c.req.matchedRoutes.forEach(({ handler, method, path }, i) => {374   *     const name = handler.name || (handler.length < 2 ? '[handler]' : '[middleware]')375   *     console.log(376   *       method,377   *       ' ',378   *       path,379   *       ' '.repeat(Math.max(10 - path.length, 0)),380   *       name,381   *       i === c.req.routeIndex ? '<- respond from here' : ''382   *     )383   *   })384   * })385   * ```386   */387  get matchedRoutes(): RouterRoute[] {388    return this.#matchResult[0].map(([[, route]]) => route)389  }390391  /**392   * `routePath()` can retrieve the path registered within the handler393   *394   * @see {@link https://hono.dev/docs/api/request#routepath}395   *396   * @example397   * ```ts398   * app.get('/posts/:id', (c) => {399   *   return c.json({ path: c.req.routePath })400   * })401   * ```402   */403  get routePath(): string {404    return this.#matchResult[0].map(([[, route]]) => route)[this.routeIndex].path405  }406}