Skip to content
Myr

request.ts

This file

Path

src/request.ts

406 lines · 10.3 KiB · TypeScript

Last changed by

fix(req): correct `c.req.param` decodes invalid percent strings (#3573)Yusuke Wadabefore adoption2bde76d

History of this file

Take it

The walk stopped after 200 commits: lines older than 7ee829b point at it.

v4.4.7Yusuke Wadabefore adoption7ee829b

lines 1–13why, one step back
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'

feat(header): suggest name of header and combine in one file (#3577)EdamAmexbefore adoptione7732a5

line 14why, one step back
14import type { CustomHeader, RequestHeader } from './utils/headers'

v4.4.7Yusuke Wadabefore adoption7ee829b

line 15why, one step back
15import type { Simplify, UnionToIntersection } from './utils/types'

fix(req): correct `c.req.param` decodes invalid percent strings (#3573)Yusuke Wadabefore adoption2bde76d

line 16why, one step back
16import { decodeURIComponent_, getQueryParam, getQueryParams, tryDecode } from './utils/url'

v4.4.7Yusuke Wadabefore adoption7ee829b

lines 17–26why, one step back
17
18type Body = {19 json: any20 text: string21 arrayBuffer: ArrayBuffer22 blob: Blob23 formData: FormData24}25type BodyCache = Partial<Body & { parsedBody: BodyData }>26

fix(req): correct `c.req.param` decodes invalid percent strings (#3573)Yusuke Wadabefore adoption2bde76d

lines 27–28why, one step back
27const tryDecodeURIComponent = (str: string) => tryDecode(str, decodeURIComponent_)
28

v4.4.7Yusuke Wadabefore adoption7ee829b

lines 29–32why, one step back
29export class HonoRequest<P extends string = '/', I extends Input['out'] = {}> {
30 /**31 * `.raw` can get the raw Request object.32 *

chore: update outdated links in JSDoc (#3089)ryubefore adoption28de9b3

line 33why, one step back
33 * @see {@link https://hono.dev/docs/api/request#raw}

v4.4.7Yusuke Wadabefore adoption7ee829b

lines 34–51why, one step back
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 *

chore: update outdated links in JSDoc (#3089)ryubefore adoption28de9b3

line 52why, one step back
52 * @see {@link https://hono.dev/docs/api/request#path}

v4.4.7Yusuke Wadabefore adoption7ee829b

lines 53–77why, one step back
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 *

chore: update outdated links in JSDoc (#3089)ryubefore adoption28de9b3

line 78why, one step back
78 * @see {@link https://hono.dev/docs/api/routing#path-parameter}

v4.4.7Yusuke Wadabefore adoption7ee829b

lines 79–99why, one step back
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 private getDecodedParam(key: string): string | undefined {98 const paramKey = this.#matchResult[0][this.routeIndex][1][key]99 const param = this.getParamValue(paramKey)

fix(req): correct `c.req.param` decodes invalid percent strings (#3573)Yusuke Wadabefore adoption2bde76d

line 100why, one step back
100 return param ? (/\%/.test(param) ? tryDecodeURIComponent(param) : param) : undefined

v4.4.7Yusuke Wadabefore adoption7ee829b

lines 101–109why, one step back
101 }
102103 private 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') {

fix(req): correct `c.req.param` decodes invalid percent strings (#3573)Yusuke Wadabefore adoption2bde76d

line 110why, one step back
110 decoded[key] = /\%/.test(value) ? tryDecodeURIComponent(value) : value

v4.4.7Yusuke Wadabefore adoption7ee829b

lines 111–123why, one step back
111 }
112 }113114 return decoded115 }116117 private 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 *

chore: update outdated links in JSDoc (#3089)ryubefore adoption28de9b3

line 124why, one step back
124 * @see {@link https://hono.dev/docs/api/request#query}

v4.4.7Yusuke Wadabefore adoption7ee829b

lines 125–147why, one step back
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 *

chore: update outdated links in JSDoc (#3089)ryubefore adoption28de9b3

line 148why, one step back
148 * @see {@link https://hono.dev/docs/api/request#queries}

v4.4.7Yusuke Wadabefore adoption7ee829b

lines 149–166why, one step back
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 *

chore: update outdated links in JSDoc (#3089)ryubefore adoption28de9b3

line 167why, one step back
167 * @see {@link https://hono.dev/docs/api/request#header}

v4.4.7Yusuke Wadabefore adoption7ee829b

lines 168–175why, one step back
168 *
169 * @example170 * ```ts171 * app.get('/', (c) => {172 * const userAgent = c.req.header('User-Agent')173 * })174 * ```175 */

feat(header): suggest name of header and combine in one file (#3577)EdamAmexbefore adoptione7732a5

line 176why, one step back
176 header(name: RequestHeader): string | undefined

v4.4.7Yusuke Wadabefore adoption7ee829b

line 177why, one step back
177 header(name: string): string | undefined

feat(header): suggest name of header and combine in one file (#3577)EdamAmexbefore adoptione7732a5

line 178why, one step back
178 header(): Record<RequestHeader | (string & CustomHeader), string>

v4.4.7Yusuke Wadabefore adoption7ee829b

lines 179–193why, one step back
179 header(name?: string) {
180 if (name) {181 return this.raw.headers.get(name.toLowerCase()) ?? 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 *

chore: update outdated links in JSDoc (#3089)ryubefore adoption28de9b3

line 194why, one step back
194 * @see {@link https://hono.dev/docs/api/request#parsebody}

v4.4.7Yusuke Wadabefore adoption7ee829b

lines 195–234why, one step back
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 private 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 *

chore: update outdated links in JSDoc (#3089)ryubefore adoption28de9b3

line 235why, one step back
235 * @see {@link https://hono.dev/docs/api/request#json}

v4.4.7Yusuke Wadabefore adoption7ee829b

lines 236–250why, one step back
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 *

chore: update outdated links in JSDoc (#3089)ryubefore adoption28de9b3

line 251why, one step back
251 * @see {@link https://hono.dev/docs/api/request#text}

v4.4.7Yusuke Wadabefore adoption7ee829b

lines 252–266why, one step back
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 *

chore: update outdated links in JSDoc (#3089)ryubefore adoption28de9b3

line 267why, one step back
267 * @see {@link https://hono.dev/docs/api/request#arraybuffer}

v4.4.7Yusuke Wadabefore adoption7ee829b

lines 268–287why, one step back
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 * ```

chore: update outdated links in JSDoc (#3089)ryubefore adoption28de9b3

line 288why, one step back
288 * @see https://hono.dev/docs/api/request#blob

v4.4.7Yusuke Wadabefore adoption7ee829b

lines 289–301why, one step back
289 */
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 * ```

chore: update outdated links in JSDoc (#3089)ryubefore adoption28de9b3

line 302why, one step back
302 * @see https://hono.dev/docs/api/request#formdata

v4.4.7Yusuke Wadabefore adoption7ee829b

lines 303–323why, one step back
303 */
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 *

chore: update outdated links in JSDoc (#3089)ryubefore adoption28de9b3

line 324why, one step back
324 * @see https://hono.dev/docs/api/request#valid

v4.4.7Yusuke Wadabefore adoption7ee829b

lines 325–333why, one step back
325 */
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 *

chore: update outdated links in JSDoc (#3089)ryubefore adoption28de9b3

line 334why, one step back
334 * @see {@link https://hono.dev/docs/api/request#url}

v4.4.7Yusuke Wadabefore adoption7ee829b

lines 335–350why, one step back
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 *

chore: update outdated links in JSDoc (#3089)ryubefore adoption28de9b3

line 351why, one step back
351 * @see {@link https://hono.dev/docs/api/request#method}

v4.4.7Yusuke Wadabefore adoption7ee829b

lines 352–366why, one step back
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 *

chore: update outdated links in JSDoc (#3089)ryubefore adoption28de9b3

line 367why, one step back
367 * @see {@link https://hono.dev/docs/api/request#matchedroutes}

v4.4.7Yusuke Wadabefore adoption7ee829b

lines 368–393why, one step back
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 *

chore: update outdated links in JSDoc (#3089)ryubefore adoption28de9b3

line 394why, one step back
394 * @see {@link https://hono.dev/docs/api/request#routepath}

v4.4.7Yusuke Wadabefore adoption7ee829b

lines 395–406why, one step back
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}