request.ts
This file
Path
src/request.ts
487 lines 路 13.0 KiB 路 TypeScript
Last changed by
Merge pull request #4461 from honojs/nextYusuke Wadabefore adoptionf0c0377
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 & { parsedBody: BodyData }>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>>(key: P2 extends `${infer _}?` ? never : P2): string95 param<P2 extends RemoveQuestion<ParamKeys<P>> = RemoveQuestion<ParamKeys<P>>>(96 key: P297 ): string | undefined98 param(key: string): string | undefined99 param<P2 extends string = P>(): Simplify<UnionToIntersection<ParamKeyToRecord<ParamKeys<P2>>>>100 param(key?: string): unknown {101 return key ? this.#getDecodedParam(key) : this.#getAllDecodedParams()102 }103104 #getDecodedParam(key: string): string | undefined {105 const paramKey = this.#matchResult[0][this.routeIndex][1][key]106 const param = this.#getParamValue(paramKey)107 return param && /\%/.test(param) ? tryDecodeURIComponent(param) : param108 }109110 #getAllDecodedParams(): Record<string, string> {111 const decoded: Record<string, string> = {}112113 const keys = Object.keys(this.#matchResult[0][this.routeIndex][1])114 for (const key of keys) {115 const value = this.#getParamValue(this.#matchResult[0][this.routeIndex][1][key])116 if (value !== undefined) {117 decoded[key] = /\%/.test(value) ? tryDecodeURIComponent(value) : value118 }119 }120121 return decoded122 }123124 #getParamValue(paramKey: any): string | undefined {125 return this.#matchResult[1] ? this.#matchResult[1][paramKey as any] : paramKey126 }127128 /**129 * `.query()` can get querystring parameters.130 *131 * @see {@link https://hono.dev/docs/api/request#query}132 *133 * @example134 * ```ts135 * // Query params136 * app.get('/search', (c) => {137 * const query = c.req.query('q')138 * })139 *140 * // Get all params at once141 * app.get('/search', (c) => {142 * const { q, limit, offset } = c.req.query()143 * })144 * ```145 */146 query(key: string): string | undefined147 query(): Record<string, string>148 query(key?: string) {149 return getQueryParam(this.url, key)150 }151152 /**153 * `.queries()` can get multiple querystring parameter values, e.g. /search?tags=A&tags=B154 *155 * @see {@link https://hono.dev/docs/api/request#queries}156 *157 * @example158 * ```ts159 * app.get('/search', (c) => {160 * // tags will be string[]161 * const tags = c.req.queries('tags')162 * })163 * ```164 */165 queries(key: string): string[] | undefined166 queries(): Record<string, string[]>167 queries(key?: string) {168 return getQueryParams(this.url, key)169 }170171 /**172 * `.header()` can get the request header value.173 *174 * @see {@link https://hono.dev/docs/api/request#header}175 *176 * @example177 * ```ts178 * app.get('/', (c) => {179 * const userAgent = c.req.header('User-Agent')180 * })181 * ```182 */183 header(name: RequestHeader): string | undefined184 header(name: string): string | undefined185 header(): Record<RequestHeader | (string & CustomHeader), string>186 header(name?: string) {187 if (name) {188 return this.raw.headers.get(name) ?? undefined189 }190191 const headerData: Record<string, string | undefined> = {}192 this.raw.headers.forEach((value, key) => {193 headerData[key] = value194 })195 return headerData196 }197198 /**199 * `.parseBody()` can parse Request body of type `multipart/form-data` or `application/x-www-form-urlencoded`200 *201 * @see {@link https://hono.dev/docs/api/request#parsebody}202 *203 * @example204 * ```ts205 * app.post('/entry', async (c) => {206 * const body = await c.req.parseBody()207 * })208 * ```209 */210 async parseBody<Options extends Partial<ParseBodyOptions>, T extends BodyData<Options>>(211 options?: Options212 ): Promise<T>213 async parseBody<T extends BodyData>(options?: Partial<ParseBodyOptions>): Promise<T>214 async parseBody(options?: Partial<ParseBodyOptions>) {215 return (this.bodyCache.parsedBody ??= await parseBody(this, options))216 }217218 #cachedBody = (key: keyof Body) => {219 const { bodyCache, raw } = this220 const cachedBody = bodyCache[key]221222 if (cachedBody) {223 return cachedBody224 }225226 const anyCachedKey = Object.keys(bodyCache)[0]227 if (anyCachedKey) {228 return (bodyCache[anyCachedKey as keyof Body] as Promise<BodyInit>).then((body) => {229 if (anyCachedKey === 'json') {230 body = JSON.stringify(body)231 }232 return new Response(body)[key]()233 })234 }235236 return (bodyCache[key] = raw[key]())237 }238239 /**240 * `.json()` can parse Request body of type `application/json`241 *242 * @see {@link https://hono.dev/docs/api/request#json}243 *244 * @example245 * ```ts246 * app.post('/entry', async (c) => {247 * const body = await c.req.json()248 * })249 * ```250 */251 json<T = any>(): Promise<T> {252 return this.#cachedBody('text').then((text: string) => JSON.parse(text))253 }254255 /**256 * `.text()` can parse Request body of type `text/plain`257 *258 * @see {@link https://hono.dev/docs/api/request#text}259 *260 * @example261 * ```ts262 * app.post('/entry', async (c) => {263 * const body = await c.req.text()264 * })265 * ```266 */267 text(): Promise<string> {268 return this.#cachedBody('text')269 }270271 /**272 * `.arrayBuffer()` parse Request body as an `ArrayBuffer`273 *274 * @see {@link https://hono.dev/docs/api/request#arraybuffer}275 *276 * @example277 * ```ts278 * app.post('/entry', async (c) => {279 * const body = await c.req.arrayBuffer()280 * })281 * ```282 */283 arrayBuffer(): Promise<ArrayBuffer> {284 return this.#cachedBody('arrayBuffer')285 }286287 /**288 * Parses the request body as a `Blob`.289 * @example290 * ```ts291 * app.post('/entry', async (c) => {292 * const body = await c.req.blob();293 * });294 * ```295 * @see https://hono.dev/docs/api/request#blob296 */297 blob(): Promise<Blob> {298 return this.#cachedBody('blob')299 }300301 /**302 * Parses the request body as `FormData`.303 * @example304 * ```ts305 * app.post('/entry', async (c) => {306 * const body = await c.req.formData();307 * });308 * ```309 * @see https://hono.dev/docs/api/request#formdata310 */311 formData(): Promise<FormData> {312 return this.#cachedBody('formData')313 }314315 /**316 * Adds validated data to the request.317 *318 * @param target - The target of the validation.319 * @param data - The validated data to add.320 */321 addValidatedData(target: keyof ValidationTargets, data: {}) {322 this.#validatedData[target] = data323 }324325 /**326 * Gets validated data from the request.327 *328 * @param target - The target of the validation.329 * @returns The validated data.330 *331 * @see https://hono.dev/docs/api/request#valid332 */333 valid<T extends keyof I & keyof ValidationTargets>(target: T): InputToDataByTarget<I, T>334 valid(target: keyof ValidationTargets) {335 return this.#validatedData[target] as unknown336 }337338 /**339 * `.url()` can get the request url strings.340 *341 * @see {@link https://hono.dev/docs/api/request#url}342 *343 * @example344 * ```ts345 * app.get('/about/me', (c) => {346 * const url = c.req.url // `http://localhost:8787/about/me`347 * ...348 * })349 * ```350 */351 get url(): string {352 return this.raw.url353 }354355 /**356 * `.method()` can get the method name of the request.357 *358 * @see {@link https://hono.dev/docs/api/request#method}359 *360 * @example361 * ```ts362 * app.get('/about/me', (c) => {363 * const method = c.req.method // `GET`364 * })365 * ```366 */367 get method(): string {368 return this.raw.method369 }370371 get [GET_MATCH_RESULT](): Result<[unknown, RouterRoute]> {372 return this.#matchResult373 }374375 /**376 * `.matchedRoutes()` can return a matched route in the handler377 *378 * @deprecated379 *380 * Use matchedRoutes helper defined in "hono/route" instead.381 *382 * @see {@link https://hono.dev/docs/api/request#matchedroutes}383 *384 * @example385 * ```ts386 * app.use('*', async function logger(c, next) {387 * await next()388 * c.req.matchedRoutes.forEach(({ handler, method, path }, i) => {389 * const name = handler.name || (handler.length < 2 ? '[handler]' : '[middleware]')390 * console.log(391 * method,392 * ' ',393 * path,394 * ' '.repeat(Math.max(10 - path.length, 0)),395 * name,396 * i === c.req.routeIndex ? '<- respond from here' : ''397 * )398 * })399 * })400 * ```401 */402 get matchedRoutes(): RouterRoute[] {403 return this.#matchResult[0].map(([[, route]]) => route)404 }405406 /**407 * `routePath()` can retrieve the path registered within the handler408 *409 * @deprecated410 *411 * Use routePath helper defined in "hono/route" instead.412 *413 * @see {@link https://hono.dev/docs/api/request#routepath}414 *415 * @example416 * ```ts417 * app.get('/posts/:id', (c) => {418 * return c.json({ path: c.req.routePath })419 * })420 * ```421 */422 get routePath(): string {423 return this.#matchResult[0].map(([[, route]]) => route)[this.routeIndex].path424 }425}426427/**428 * Clones a HonoRequest's underlying raw Request object.429 *430 * This utility handles both consumed and unconsumed request bodies:431 * - If the request body hasn't been consumed, it uses the native `clone()` method432 * - If the request body has been consumed, it reconstructs a new Request using cached body data433 *434 * This is particularly useful when you need to:435 * - Process the same request body multiple times436 * - Pass requests to external services after validation437 *438 * @param req - The HonoRequest object to clone439 * @returns A Promise that resolves to a new Request object with the same properties440 * @throws {HTTPException} If the request body was consumed directly via `req.raw`441 * without using HonoRequest methods (e.g., `req.json()`, `req.text()`), making it442 * impossible to reconstruct the body from cache443 *444 * @example445 * ```ts446 * // Clone after consuming the body (e.g., after validation)447 * app.post('/forward',448 * validator('json', (data) => data),449 * async (c) => {450 * const validated = c.req.valid('json')451 * // Body has been consumed, but cloneRawRequest still works452 * const clonedReq = await cloneRawRequest(c.req)453 * return fetch('http://backend-service.com', clonedReq)454 * }455 * )456 * ```457 */458export const cloneRawRequest = async (req: HonoRequest): Promise<Request> => {459 if (!req.raw.bodyUsed) {460 return req.raw.clone()461 }462463 const cacheKey = (Object.keys(req.bodyCache) as Array<keyof Body>)[0]464 if (!cacheKey) {465 throw new HTTPException(500, {466 message:467 '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.',468 })469 }470471 const requestInit: RequiredRequestInit = {472 body: await req[cacheKey](),473 cache: req.raw.cache,474 credentials: req.raw.credentials,475 headers: req.header(),476 integrity: req.raw.integrity,477 keepalive: req.raw.keepalive,478 method: req.method,479 mode: req.raw.mode,480 redirect: req.raw.redirect,481 referrer: req.raw.referrer,482 referrerPolicy: req.raw.referrerPolicy,483 signal: req.raw.signal,484 }485486 return new Request(req.url, requestInit)487}