request.ts
This file
Path
src/request.ts
338 lines · 8.7 KiB · TypeScript
Last changed by
Merge pull request #2167 from honojs/v4Yusuke Wadabefore adoption2c44ad7
History of this fileTake it
The walk stopped after 200 commits: lines older than ba04dac point at it.
Merge pull request #1436 from honojs/nextYusuke Wadabefore adoptionba04dac
line 1why, one step back1/* eslint-disable @typescript-eslint/no-explicit-any */Merge pull request #1774 from honojs/nextYusuke Wadabefore adoptionb21f33c
line 2why, one step back2import type { Result } from './router'Merge pull request #1436 from honojs/nextYusuke Wadabefore adoptionba04dac
lines 3–10why, one step back3import type {4 Input,5 InputToDataByTarget,6 ParamKeys,7 ParamKeyToRecord,8 RemoveQuestion,9 UndefinedIfHavingQuestion,10 ValidationTargets,Merge pull request #1774 from honojs/nextYusuke Wadabefore adoptionb21f33c
line 11why, one step back11 RouterRoute,Merge pull request #1436 from honojs/nextYusuke Wadabefore adoptionba04dac
lines 12–13why, one step back12} from './types'13import { parseBody } from './utils/body'Merge pull request #1589 from honojs/nextYusuke Wadabefore adoption70d83cb
line 14why, one step back14import type { BodyData, ParseBodyOptions } from './utils/body'Merge pull request #1436 from honojs/nextYusuke Wadabefore adoptionba04dac
lines 15–27why, one step back15import type { UnionToIntersection } from './utils/types'16import { getQueryParam, getQueryParams, decodeURIComponent_ } from './utils/url'1718type Body = {19 json: any20 text: string21 arrayBuffer: ArrayBuffer22 blob: Blob23 formData: FormData24}25type BodyCache = Partial<Body & { parsedBody: BodyData }>2627export class HonoRequest<P extends string = '/', I extends Input['out'] = {}> {Merge pull request #2167 from honojs/v4Yusuke Wadabefore adoption2c44ad7
lines 28–39why, one step back28 /**29 * `.raw` can get the raw Request object.30 * @example31 * ```ts32 * // For Cloudflare Workers33 * app.post('/', async (c) => {34 * const metadata = c.req.raw.cf?.hostMetadata?35 * ...36 * })37 * ```38 * @see https://hono.dev/api/request#raw39 */Merge pull request #1436 from honojs/nextYusuke Wadabefore adoptionba04dac
lines 40–41why, one step back40 raw: Request41Merge pull request #1774 from honojs/nextYusuke Wadabefore adoptionb21f33c
lines 42–44why, one step back42 #validatedData: { [K in keyof ValidationTargets]?: {} } // Short name of validatedData43 #matchResult: Result<[unknown, RouterRoute]>44 routeIndex: number = 0Merge pull request #2167 from honojs/v4Yusuke Wadabefore adoption2c44ad7
lines 45–54why, one step back45 /**46 * `.path` can get the pathname of the request.47 * @example48 * ```ts49 * app.get('/about/me', (c) => {50 * const pathname = c.req.path // `/about/me`51 * })52 * ```53 * @see https://hono.dev/api/request#path54 */Merge pull request #1436 from honojs/nextYusuke Wadabefore adoptionba04dac
lines 55–57why, one step back55 path: string56 bodyCache: BodyCache = {}57fix: References this._s only when paramStash is passed from the router (#1715)Taku Amanobefore adoptionae3546e
lines 58–60why, one step back58 constructor(59 request: Request,60 path: string = '/',Merge pull request #1774 from honojs/nextYusuke Wadabefore adoptionb21f33c
line 61why, one step back61 matchResult: Result<[unknown, RouterRoute]> = [[]]fix: References this._s only when paramStash is passed from the router (#1715)Taku Amanobefore adoptionae3546e
line 62why, one step back62 ) {Merge pull request #1436 from honojs/nextYusuke Wadabefore adoptionba04dac
lines 63–64why, one step back63 this.raw = request64 this.path = pathMerge pull request #1774 from honojs/nextYusuke Wadabefore adoptionb21f33c
lines 65–66why, one step back65 this.#matchResult = matchResult66 this.#validatedData = {}Merge pull request #1436 from honojs/nextYusuke Wadabefore adoptionba04dac
lines 67–68why, one step back67 }68Merge pull request #2167 from honojs/v4Yusuke Wadabefore adoption2c44ad7
lines 69–78why, one step back69 /**70 * `.req.param()` gets the path parameters.71 * @example72 * ```ts73 * const name = c.req.param('name')74 * // or all parameters at once75 * const { id, comment_id } = c.req.param()76 * ```77 * @see https://hono.dev/api/routing#path-parameter78 */Merge pull request #1436 from honojs/nextYusuke Wadabefore adoptionba04dac
lines 79–83why, one step back79 param<P2 extends string = P>(80 key: RemoveQuestion<ParamKeys<P2>>81 ): UndefinedIfHavingQuestion<ParamKeys<P2>>82 param<P2 extends string = P>(): UnionToIntersection<ParamKeyToRecord<ParamKeys<P2>>>83 param(key?: string): unknown {refactor: request param (#2088)Aris Kemperbefore adoptionb0cac62
lines 84–85why, one step back84 return key ? this.getDecodedParam(key) : this.getAllDecodedParams()85 }Merge pull request #1436 from honojs/nextYusuke Wadabefore adoptionba04dac
line 86why, one step back86refactor: request param (#2088)Aris Kemperbefore adoptionb0cac62
lines 87–89why, one step back87 private getDecodedParam(key: string): string | undefined {88 const paramKey = this.#matchResult[0][this.routeIndex][1][key]89 const param = this.getParamValue(paramKey)fix: References this._s only when paramStash is passed from the router (#1715)Taku Amanobefore adoptionae3546e
line 90why, one step back90refactor: request param (#2088)Aris Kemperbefore adoptionb0cac62
lines 91–102why, one step back91 return param ? (/\%/.test(param) ? decodeURIComponent_(param) : param) : undefined92 }9394 private getAllDecodedParams(): Record<string, string> {95 const decoded: Record<string, string> = {}9697 const keys = Object.keys(this.#matchResult[0][this.routeIndex][1])98 for (const key of keys) {99 const value = this.getParamValue(this.#matchResult[0][this.routeIndex][1][key])100 if (value && typeof value === 'string') {101 decoded[key] = /\%/.test(value) ? decodeURIComponent_(value) : value102 }Merge pull request #1436 from honojs/nextYusuke Wadabefore adoptionba04dac
line 103why, one step back103 }refactor: request param (#2088)Aris Kemperbefore adoptionb0cac62
lines 104–109why, one step back104105 return decoded106 }107108 private getParamValue(paramKey: any): string | undefined {109 return this.#matchResult[1] ? this.#matchResult[1][paramKey as any] : paramKeyMerge pull request #1436 from honojs/nextYusuke Wadabefore adoptionba04dac
lines 110–111why, one step back110 }111Merge pull request #2167 from honojs/v4Yusuke Wadabefore adoption2c44ad7
lines 112–127why, one step back112 /**113 * `.query()` can get querystring parameters.114 * @example115 * ```ts116 * // Query params117 * app.get('/search', (c) => {118 * const query = c.req.query('q')119 * })120 *121 * // Get all params at once122 * app.get('/search', (c) => {123 * const { q, limit, offset } = c.req.query()124 * })125 * ```126 * @see https://hono.dev/api/request#query127 */Merge pull request #1436 from honojs/nextYusuke Wadabefore adoptionba04dac
lines 128–133why, one step back128 query(key: string): string | undefined129 query(): Record<string, string>130 query(key?: string) {131 return getQueryParam(this.url, key)132 }133Merge pull request #2167 from honojs/v4Yusuke Wadabefore adoption2c44ad7
lines 134–144why, one step back134 /**135 * `.queries()` can get multiple querystring parameter values, e.g. /search?tags=A&tags=B136 * @example137 * ```ts138 * app.get('/search', (c) => {139 * // tags will be string[]140 * const tags = c.req.queries('tags')141 * })142 * ```143 * @see https://hono.dev/api/request#queries144 */Merge pull request #1436 from honojs/nextYusuke Wadabefore adoptionba04dac
lines 145–150why, one step back145 queries(key: string): string[] | undefined146 queries(): Record<string, string[]>147 queries(key?: string) {148 return getQueryParams(this.url, key)149 }150Merge pull request #2167 from honojs/v4Yusuke Wadabefore adoption2c44ad7
lines 151–160why, one step back151 /**152 * `.header()` can get the request header value.153 * @example154 * ```ts155 * app.get('/', (c) => {156 * const userAgent = c.req.header('User-Agent')157 * })158 * ```159 * @see https://hono.dev/api/request#header160 */Merge pull request #1436 from honojs/nextYusuke Wadabefore adoptionba04dac
lines 161–163why, one step back161 header(name: string): string | undefined162 header(): Record<string, string>163 header(name?: string) {chore(lint): set `curly` rule as `all` (#2112)Yusuke Wadabefore adoptionf616ed9
lines 164–166why, one step back164 if (name) {165 return this.raw.headers.get(name.toLowerCase()) ?? undefined166 }Merge pull request #1436 from honojs/nextYusuke Wadabefore adoptionba04dac
lines 167–174why, one step back167168 const headerData: Record<string, string | undefined> = {}169 this.raw.headers.forEach((value, key) => {170 headerData[key] = value171 })172 return headerData173 }174Merge pull request #2167 from honojs/v4Yusuke Wadabefore adoption2c44ad7
lines 175–176why, one step back175 /**176 * `.parseBody()` can parse Request body of type `multipart/form-data` or `application/x-www-form-urlencoded`Merge pull request #1436 from honojs/nextYusuke Wadabefore adoptionba04dac
line 177why, one step back177 * @exampleMerge pull request #2167 from honojs/v4Yusuke Wadabefore adoption2c44ad7
lines 178–183why, one step back178 * ```ts179 * app.post('/entry', async (c) => {180 * const body = await c.req.parseBody()181 * })182 * ```183 * @see https://hono.dev/api/request#parsebodyMerge pull request #1436 from honojs/nextYusuke Wadabefore adoptionba04dac
line 184why, one step back184 */Merge pull request #1589 from honojs/nextYusuke Wadabefore adoption70d83cb
line 185why, one step back185 async parseBody<T extends BodyData = BodyData>(options?: ParseBodyOptions): Promise<T> {chore(lint): set `curly` rule as `all` (#2112)Yusuke Wadabefore adoptionf616ed9
lines 186–188why, one step back186 if (this.bodyCache.parsedBody) {187 return this.bodyCache.parsedBody as T188 }Merge pull request #1589 from honojs/nextYusuke Wadabefore adoption70d83cb
line 189why, one step back189 const parsedBody = await parseBody<T>(this, options)Merge pull request #1436 from honojs/nextYusuke Wadabefore adoptionba04dac
lines 190–196why, one step back190 this.bodyCache.parsedBody = parsedBody191 return parsedBody192 }193194 private cachedBody = (key: keyof Body) => {195 const { bodyCache, raw } = this196 const cachedBody = bodyCache[key]chore(lint): set `curly` rule as `all` (#2112)Yusuke Wadabefore adoptionf616ed9
lines 197–199why, one step back197 if (cachedBody) {198 return cachedBody199 }Merge pull request #1436 from honojs/nextYusuke Wadabefore adoptionba04dac
lines 200–211why, one step back200 /**201 * If an arrayBuffer cache is exist,202 * use it for creating a text, json, and others.203 */204 if (bodyCache.arrayBuffer) {205 return (async () => {206 return await new Response(bodyCache.arrayBuffer)[key]()207 })()208 }209 return (bodyCache[key] = raw[key]())210 }211Merge pull request #2167 from honojs/v4Yusuke Wadabefore adoption2c44ad7
lines 212–221why, one step back212 /**213 * `.json()` can parse Request body of type `application/json`214 * @example215 * ```ts216 * app.post('/entry', async (c) => {217 * const body = await c.req.json()218 * })219 * ```220 * @see https://hono.dev/api/request#json221 */Merge pull request #1436 from honojs/nextYusuke Wadabefore adoptionba04dac
lines 222–225why, one step back222 json<T = any>(): Promise<T> {223 return this.cachedBody('json')224 }225Merge pull request #2167 from honojs/v4Yusuke Wadabefore adoption2c44ad7
lines 226–235why, one step back226 /**227 * `.text()` can parse Request body of type `text/plain`228 * @example229 * ```ts230 * app.post('/entry', async (c) => {231 * const body = await c.req.text()232 * })233 * ```234 * @see https://hono.dev/api/request#text235 */Merge pull request #1436 from honojs/nextYusuke Wadabefore adoptionba04dac
lines 236–239why, one step back236 text(): Promise<string> {237 return this.cachedBody('text')238 }239Merge pull request #2167 from honojs/v4Yusuke Wadabefore adoption2c44ad7
lines 240–249why, one step back240 /**241 * `.arrayBuffer()` parse Request body as an `ArrayBuffer`242 * @example243 * ```ts244 * app.post('/entry', async (c) => {245 * const body = await c.req.arrayBuffer()246 * })247 * ```248 * @see https://hono.dev/api/request#arraybuffer249 */Merge pull request #1436 from honojs/nextYusuke Wadabefore adoptionba04dac
lines 250–262why, one step back250 arrayBuffer(): Promise<ArrayBuffer> {251 return this.cachedBody('arrayBuffer')252 }253254 blob(): Promise<Blob> {255 return this.cachedBody('blob')256 }257258 formData(): Promise<FormData> {259 return this.cachedBody('formData')260 }261262 addValidatedData(target: keyof ValidationTargets, data: {}) {Merge pull request #1774 from honojs/nextYusuke Wadabefore adoptionb21f33c
line 263why, one step back263 this.#validatedData[target] = dataMerge pull request #1436 from honojs/nextYusuke Wadabefore adoptionba04dac
lines 264–267why, one step back264 }265266 valid<T extends keyof I & keyof ValidationTargets>(target: T): InputToDataByTarget<I, T>267 valid(target: keyof ValidationTargets) {Merge pull request #1774 from honojs/nextYusuke Wadabefore adoptionb21f33c
line 268why, one step back268 return this.#validatedData[target] as unknownMerge pull request #1436 from honojs/nextYusuke Wadabefore adoptionba04dac
lines 269–270why, one step back269 }270Merge pull request #2167 from honojs/v4Yusuke Wadabefore adoption2c44ad7
lines 271–281why, one step back271 /**272 * `.url()` can get the request url strings.273 * @example274 * ```ts275 * app.get('/about/me', (c) => {276 * const url = c.req.url // `http://localhost:8787/about/me`277 * ...278 * })279 * ```280 * @see https://hono.dev/api/request#url281 */Merge pull request #1436 from honojs/nextYusuke Wadabefore adoptionba04dac
lines 282–285why, one step back282 get url() {283 return this.raw.url284 }285Merge pull request #2167 from honojs/v4Yusuke Wadabefore adoption2c44ad7
lines 286–295why, one step back286 /**287 * `.method()` can get the method name of the request.288 * @example289 * ```ts290 * app.get('/about/me', (c) => {291 * const method = c.req.method // `GET`292 * })293 * ```294 * @see https://hono.dev/api/request#method295 */Merge pull request #1436 from honojs/nextYusuke Wadabefore adoptionba04dac
lines 296–297why, one step back296 get method() {297 return this.raw.methodMerge pull request #1774 from honojs/nextYusuke Wadabefore adoptionb21f33c
lines 298–299why, one step back298 }299Merge pull request #2167 from honojs/v4Yusuke Wadabefore adoption2c44ad7
lines 300–320why, one step back300 /**301 * `.matchedRoutes()` can return a matched route in the handler302 * @example303 * ```ts304 * app.use('*', async function logger(c, next) {305 * await next()306 * c.req.matchedRoutes.forEach(({ handler, method, path }, i) => {307 * const name = handler.name || (handler.length < 2 ? '[handler]' : '[middleware]')308 * console.log(309 * method,310 * ' ',311 * path,312 * ' '.repeat(Math.max(10 - path.length, 0)),313 * name,314 * i === c.req.routeIndex ? '<- respond from here' : ''315 * )316 * })317 * })318 * ```319 * @see https://hono.dev/api/request#matchedroutes320 */Merge pull request #1774 from honojs/nextYusuke Wadabefore adoptionb21f33c
lines 321–324why, one step back321 get matchedRoutes(): RouterRoute[] {322 return this.#matchResult[0].map(([[, route]]) => route)323 }324Merge pull request #2167 from honojs/v4Yusuke Wadabefore adoption2c44ad7
lines 325–326why, one step back325 /**326 * `routePath()` can retrieve the path registered within the handlerMerge pull request #1436 from honojs/nextYusuke Wadabefore adoptionba04dac
line 327why, one step back327 * @exampleMerge pull request #2167 from honojs/v4Yusuke Wadabefore adoption2c44ad7
lines 328–330why, one step back328 * ```ts329 * app.get('/posts/:id', (c) => {330 * return c.json({ path: c.req.routePath })Merge pull request #1436 from honojs/nextYusuke Wadabefore adoptionba04dac
line 331why, one step back331 * })Merge pull request #2167 from honojs/v4Yusuke Wadabefore adoption2c44ad7
lines 332–333why, one step back332 * ```333 * @see https://hono.dev/api/request#routepathMerge pull request #1436 from honojs/nextYusuke Wadabefore adoptionba04dac
line 334why, one step back334 */Merge pull request #2167 from honojs/v4Yusuke Wadabefore adoption2c44ad7
lines 335–336why, one step back335 get routePath(): string {336 return this.#matchResult[0].map(([[, route]]) => route)[this.routeIndex].pathMerge pull request #1436 from honojs/nextYusuke Wadabefore adoptionba04dac
lines 337–338why, one step back337 }338}