Skip to content
Myr

request.ts

This file

Path

src/request.ts

347 lines · 8.9 KiB · TypeScript

Last changed by

Merge pull request #2454 from honojs/nextYusuke Wadabefore adoptioneb97ee2

History of this file

Take it

The walk stopped after 200 commits: lines older than 8addfd4 point at it.

chore: upgrading vitest to v1.0 (#1830)watanybefore adoption8addfd4

lines 1–27why, one step back
1/* eslint-disable @typescript-eslint/no-explicit-any */
2import type { Result } from './router'3import type {4 Input,5 InputToDataByTarget,6 ParamKeys,7 ParamKeyToRecord,8 RemoveQuestion,9 UndefinedIfHavingQuestion,10 ValidationTargets,11 RouterRoute,12} from './types'13import { parseBody } from './utils/body'14import type { BodyData, ParseBodyOptions } from './utils/body'15import 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 back
28 /**
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 */

chore: upgrading vitest to v1.0 (#1830)watanybefore adoption8addfd4

lines 40–44why, one step back
40 raw: Request
4142 #validatedData: { [K in keyof ValidationTargets]?: {} } // Short name of validatedData43 #matchResult: Result<[unknown, RouterRoute]>44 routeIndex: number = 0

Merge pull request #2167 from honojs/v4Yusuke Wadabefore adoption2c44ad7

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

chore: upgrading vitest to v1.0 (#1830)watanybefore adoption8addfd4

lines 55–68why, one step back
55 path: string
56 bodyCache: BodyCache = {}5758 constructor(59 request: Request,60 path: string = '/',61 matchResult: Result<[unknown, RouterRoute]> = [[]]62 ) {63 this.raw = request64 this.path = path65 this.#matchResult = matchResult66 this.#validatedData = {}67 }68

Merge pull request #2167 from honojs/v4Yusuke Wadabefore adoption2c44ad7

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

chore: upgrading vitest to v1.0 (#1830)watanybefore adoption8addfd4

lines 79–83why, one step back
79 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 back
84 return key ? this.getDecodedParam(key) : this.getAllDecodedParams()
85 }

chore: upgrading vitest to v1.0 (#1830)watanybefore adoption8addfd4

line 86why, one step back
86

refactor: request param (#2088)Aris Kemperbefore adoptionb0cac62

lines 87–89why, one step back
87 private getDecodedParam(key: string): string | undefined {
88 const paramKey = this.#matchResult[0][this.routeIndex][1][key]89 const param = this.getParamValue(paramKey)

chore: upgrading vitest to v1.0 (#1830)watanybefore adoption8addfd4

line 90why, one step back
90

refactor: request param (#2088)Aris Kemperbefore adoptionb0cac62

lines 91–102why, one step back
91 return param ? (/\%/.test(param) ? decodeURIComponent_(param) : param) : undefined
92 }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 }

chore: upgrading vitest to v1.0 (#1830)watanybefore adoption8addfd4

line 103why, one step back
103 }

refactor: request param (#2088)Aris Kemperbefore adoptionb0cac62

lines 104–109why, one step back
104
105 return decoded106 }107108 private getParamValue(paramKey: any): string | undefined {109 return this.#matchResult[1] ? this.#matchResult[1][paramKey as any] : paramKey

chore: upgrading vitest to v1.0 (#1830)watanybefore adoption8addfd4

lines 110–111why, one step back
110 }
111

Merge pull request #2167 from honojs/v4Yusuke Wadabefore adoption2c44ad7

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

chore: upgrading vitest to v1.0 (#1830)watanybefore adoption8addfd4

lines 128–133why, one step back
128 query(key: string): string | undefined
129 query(): Record<string, string>130 query(key?: string) {131 return getQueryParam(this.url, key)132 }133

Merge pull request #2167 from honojs/v4Yusuke Wadabefore adoption2c44ad7

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

chore: upgrading vitest to v1.0 (#1830)watanybefore adoption8addfd4

lines 145–150why, one step back
145 queries(key: string): string[] | undefined
146 queries(): Record<string, string[]>147 queries(key?: string) {148 return getQueryParams(this.url, key)149 }150

Merge pull request #2167 from honojs/v4Yusuke Wadabefore adoption2c44ad7

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

chore: upgrading vitest to v1.0 (#1830)watanybefore adoption8addfd4

lines 161–163why, one step back
161 header(name: string): string | undefined
162 header(): Record<string, string>163 header(name?: string) {

chore(lint): set `curly` rule as `all` (#2112)Yusuke Wadabefore adoptionf616ed9

lines 164–166why, one step back
164 if (name) {
165 return this.raw.headers.get(name.toLowerCase()) ?? undefined166 }

chore: upgrading vitest to v1.0 (#1830)watanybefore adoption8addfd4

lines 167–174why, one step back
167
168 const headerData: Record<string, string | undefined> = {}169 this.raw.headers.forEach((value, key) => {170 headerData[key] = value171 })172 return headerData173 }174

Merge pull request #2167 from honojs/v4Yusuke Wadabefore adoption2c44ad7

lines 175–176why, one step back
175 /**
176 * `.parseBody()` can parse Request body of type `multipart/form-data` or `application/x-www-form-urlencoded`

chore: upgrading vitest to v1.0 (#1830)watanybefore adoption8addfd4

line 177why, one step back
177 * @example

Merge pull request #2167 from honojs/v4Yusuke Wadabefore adoption2c44ad7

lines 178–183why, one step back
178 * ```ts
179 * app.post('/entry', async (c) => {180 * const body = await c.req.parseBody()181 * })182 * ```183 * @see https://hono.dev/api/request#parsebody

chore: upgrading vitest to v1.0 (#1830)watanybefore adoption8addfd4

lines 184–185why, one step back
184 */
185 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 back
186 if (this.bodyCache.parsedBody) {
187 return this.bodyCache.parsedBody as T188 }

chore: upgrading vitest to v1.0 (#1830)watanybefore adoption8addfd4

lines 189–196why, one step back
189 const parsedBody = await parseBody<T>(this, options)
190 this.bodyCache.parsedBody = parsedBody191 return parsedBody192 }193194 private cachedBody = (key: keyof Body) => {195 const { bodyCache, raw } = this196 const cachedBody = bodyCache[key]

Merge pull request #2454 from honojs/nextYusuke Wadabefore adoptioneb97ee2

line 197why, one step back
197

chore(lint): set `curly` rule as `all` (#2112)Yusuke Wadabefore adoptionf616ed9

lines 198–200why, one step back
198 if (cachedBody) {
199 return cachedBody200 }

Merge pull request #2454 from honojs/nextYusuke Wadabefore adoptioneb97ee2

lines 201–215why, one step back
201
202 if (!bodyCache[key]) {203 for (const keyOfBodyCache of Object.keys(bodyCache)) {204 if (keyOfBodyCache === 'parsedBody') {205 continue206 }207 return (async () => {208 // @ts-expect-error bodyCache[keyOfBodyCache] can be passed as a body209 let body = await bodyCache[keyOfBodyCache]210 if (keyOfBodyCache === 'json') {211 body = JSON.stringify(body)212 }213 return await new Response(body)[key]()214 })()215 }

chore: upgrading vitest to v1.0 (#1830)watanybefore adoption8addfd4

line 216why, one step back
216 }

Merge pull request #2454 from honojs/nextYusuke Wadabefore adoptioneb97ee2

line 217why, one step back
217

chore: upgrading vitest to v1.0 (#1830)watanybefore adoption8addfd4

lines 218–220why, one step back
218 return (bodyCache[key] = raw[key]())
219 }220

Merge pull request #2167 from honojs/v4Yusuke Wadabefore adoption2c44ad7

lines 221–230why, one step back
221 /**
222 * `.json()` can parse Request body of type `application/json`223 * @example224 * ```ts225 * app.post('/entry', async (c) => {226 * const body = await c.req.json()227 * })228 * ```229 * @see https://hono.dev/api/request#json230 */

chore: upgrading vitest to v1.0 (#1830)watanybefore adoption8addfd4

lines 231–234why, one step back
231 json<T = any>(): Promise<T> {
232 return this.cachedBody('json')233 }234

Merge pull request #2167 from honojs/v4Yusuke Wadabefore adoption2c44ad7

lines 235–244why, one step back
235 /**
236 * `.text()` can parse Request body of type `text/plain`237 * @example238 * ```ts239 * app.post('/entry', async (c) => {240 * const body = await c.req.text()241 * })242 * ```243 * @see https://hono.dev/api/request#text244 */

chore: upgrading vitest to v1.0 (#1830)watanybefore adoption8addfd4

lines 245–248why, one step back
245 text(): Promise<string> {
246 return this.cachedBody('text')247 }248

Merge pull request #2167 from honojs/v4Yusuke Wadabefore adoption2c44ad7

lines 249–258why, one step back
249 /**
250 * `.arrayBuffer()` parse Request body as an `ArrayBuffer`251 * @example252 * ```ts253 * app.post('/entry', async (c) => {254 * const body = await c.req.arrayBuffer()255 * })256 * ```257 * @see https://hono.dev/api/request#arraybuffer258 */

chore: upgrading vitest to v1.0 (#1830)watanybefore adoption8addfd4

lines 259–279why, one step back
259 arrayBuffer(): Promise<ArrayBuffer> {
260 return this.cachedBody('arrayBuffer')261 }262263 blob(): Promise<Blob> {264 return this.cachedBody('blob')265 }266267 formData(): Promise<FormData> {268 return this.cachedBody('formData')269 }270271 addValidatedData(target: keyof ValidationTargets, data: {}) {272 this.#validatedData[target] = data273 }274275 valid<T extends keyof I & keyof ValidationTargets>(target: T): InputToDataByTarget<I, T>276 valid(target: keyof ValidationTargets) {277 return this.#validatedData[target] as unknown278 }279

Merge pull request #2167 from honojs/v4Yusuke Wadabefore adoption2c44ad7

lines 280–290why, one step back
280 /**
281 * `.url()` can get the request url strings.282 * @example283 * ```ts284 * app.get('/about/me', (c) => {285 * const url = c.req.url // `http://localhost:8787/about/me`286 * ...287 * })288 * ```289 * @see https://hono.dev/api/request#url290 */

chore: upgrading vitest to v1.0 (#1830)watanybefore adoption8addfd4

lines 291–294why, one step back
291 get url() {
292 return this.raw.url293 }294

Merge pull request #2167 from honojs/v4Yusuke Wadabefore adoption2c44ad7

lines 295–304why, one step back
295 /**
296 * `.method()` can get the method name of the request.297 * @example298 * ```ts299 * app.get('/about/me', (c) => {300 * const method = c.req.method // `GET`301 * })302 * ```303 * @see https://hono.dev/api/request#method304 */

chore: upgrading vitest to v1.0 (#1830)watanybefore adoption8addfd4

lines 305–308why, one step back
305 get method() {
306 return this.raw.method307 }308

Merge pull request #2167 from honojs/v4Yusuke Wadabefore adoption2c44ad7

lines 309–329why, one step back
309 /**
310 * `.matchedRoutes()` can return a matched route in the handler311 * @example312 * ```ts313 * app.use('*', async function logger(c, next) {314 * await next()315 * c.req.matchedRoutes.forEach(({ handler, method, path }, i) => {316 * const name = handler.name || (handler.length < 2 ? '[handler]' : '[middleware]')317 * console.log(318 * method,319 * ' ',320 * path,321 * ' '.repeat(Math.max(10 - path.length, 0)),322 * name,323 * i === c.req.routeIndex ? '<- respond from here' : ''324 * )325 * })326 * })327 * ```328 * @see https://hono.dev/api/request#matchedroutes329 */

chore: upgrading vitest to v1.0 (#1830)watanybefore adoption8addfd4

lines 330–333why, one step back
330 get matchedRoutes(): RouterRoute[] {
331 return this.#matchResult[0].map(([[, route]]) => route)332 }333

Merge pull request #2167 from honojs/v4Yusuke Wadabefore adoption2c44ad7

lines 334–335why, one step back
334 /**
335 * `routePath()` can retrieve the path registered within the handler

chore: upgrading vitest to v1.0 (#1830)watanybefore adoption8addfd4

line 336why, one step back
336 * @example

Merge pull request #2167 from honojs/v4Yusuke Wadabefore adoption2c44ad7

lines 337–339why, one step back
337 * ```ts
338 * app.get('/posts/:id', (c) => {339 * return c.json({ path: c.req.routePath })

chore: upgrading vitest to v1.0 (#1830)watanybefore adoption8addfd4

line 340why, one step back
340 * })

Merge pull request #2167 from honojs/v4Yusuke Wadabefore adoption2c44ad7

lines 341–342why, one step back
341 * ```
342 * @see https://hono.dev/api/request#routepath

chore: upgrading vitest to v1.0 (#1830)watanybefore adoption8addfd4

line 343why, one step back
343 */

Merge pull request #2167 from honojs/v4Yusuke Wadabefore adoption2c44ad7

lines 344–345why, one step back
344 get routePath(): string {
345 return this.#matchResult[0].map(([[, route]]) => route)[this.routeIndex].path

chore: upgrading vitest to v1.0 (#1830)watanybefore adoption8addfd4

lines 346–347why, one step back
346 }
347}