deno.land / x / hono@v4.2.5 / request.ts

نووسراو ببینە
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
/* eslint-disable @typescript-eslint/no-explicit-any */import type { Result } from './router.ts'import type { Input, InputToDataByTarget, ParamKeys, ParamKeyToRecord, RemoveQuestion, UndefinedIfHavingQuestion, ValidationTargets, RouterRoute,} from './types.ts'import { parseBody } from './utils/body.ts'import type { BodyData, ParseBodyOptions } from './utils/body.ts'import type { UnionToIntersection } from './utils/types.ts'import { getQueryParam, getQueryParams, decodeURIComponent_ } from './utils/url.ts'
type Body = { json: any text: string arrayBuffer: ArrayBuffer blob: Blob formData: FormData}type BodyCache = Partial<Body & { parsedBody: BodyData }>
export class HonoRequest<P extends string = '/', I extends Input['out'] = {}> { /** * `.raw` can get the raw Request object. * @example * ```ts * // For Cloudflare Workers * app.post('/', async (c) => { * const metadata = c.req.raw.cf?.hostMetadata? * ... * }) * ``` * @see https://hono.dev/api/request#raw */ raw: Request
#validatedData: { [K in keyof ValidationTargets]?: {} } // Short name of validatedData #matchResult: Result<[unknown, RouterRoute]> routeIndex: number = 0 /** * `.path` can get the pathname of the request. * @example * ```ts * app.get('/about/me', (c) => { * const pathname = c.req.path // `/about/me` * }) * ``` * @see https://hono.dev/api/request#path */ path: string bodyCache: BodyCache = {}
constructor( request: Request, path: string = '/', matchResult: Result<[unknown, RouterRoute]> = [[]] ) { this.raw = request this.path = path this.#matchResult = matchResult this.#validatedData = {} }
/** * `.req.param()` gets the path parameters. * @example * ```ts * const name = c.req.param('name') * // or all parameters at once * const { id, comment_id } = c.req.param() * ``` * @see https://hono.dev/api/routing#path-parameter */ param<P2 extends string = P>( key: RemoveQuestion<ParamKeys<P2>> ): UndefinedIfHavingQuestion<ParamKeys<P2>> param<P2 extends string = P>(): UnionToIntersection<ParamKeyToRecord<ParamKeys<P2>>> param(key?: string): unknown { return key ? this.getDecodedParam(key) : this.getAllDecodedParams() }
private getDecodedParam(key: string): string | undefined { const paramKey = this.#matchResult[0][this.routeIndex][1][key] const param = this.getParamValue(paramKey)
return param ? (/\%/.test(param) ? decodeURIComponent_(param) : param) : undefined }
private getAllDecodedParams(): Record<string, string> { const decoded: Record<string, string> = {}
const keys = Object.keys(this.#matchResult[0][this.routeIndex][1]) for (const key of keys) { const value = this.getParamValue(this.#matchResult[0][this.routeIndex][1][key]) if (value && typeof value === 'string') { decoded[key] = /\%/.test(value) ? decodeURIComponent_(value) : value } }
return decoded }
private getParamValue(paramKey: any): string | undefined { return this.#matchResult[1] ? this.#matchResult[1][paramKey as any] : paramKey }
/** * `.query()` can get querystring parameters. * @example * ```ts * // Query params * app.get('/search', (c) => { * const query = c.req.query('q') * }) * * // Get all params at once * app.get('/search', (c) => { * const { q, limit, offset } = c.req.query() * }) * ``` * @see https://hono.dev/api/request#query */ query(key: string): string | undefined query(): Record<string, string> query(key?: string) { return getQueryParam(this.url, key) }
/** * `.queries()` can get multiple querystring parameter values, e.g. /search?tags=A&tags=B * @example * ```ts * app.get('/search', (c) => { * // tags will be string[] * const tags = c.req.queries('tags') * }) * ``` * @see https://hono.dev/api/request#queries */ queries(key: string): string[] | undefined queries(): Record<string, string[]> queries(key?: string) { return getQueryParams(this.url, key) }
/** * `.header()` can get the request header value. * @example * ```ts * app.get('/', (c) => { * const userAgent = c.req.header('User-Agent') * }) * ``` * @see https://hono.dev/api/request#header */ header(name: string): string | undefined header(): Record<string, string> header(name?: string) { if (name) { return this.raw.headers.get(name.toLowerCase()) ?? undefined }
const headerData: Record<string, string | undefined> = {} this.raw.headers.forEach((value, key) => { headerData[key] = value }) return headerData }
/** * `.parseBody()` can parse Request body of type `multipart/form-data` or `application/x-www-form-urlencoded` * @example * ```ts * app.post('/entry', async (c) => { * const body = await c.req.parseBody() * }) * ``` * @see https://hono.dev/api/request#parsebody */ async parseBody<T extends BodyData = BodyData>(options?: ParseBodyOptions): Promise<T> { if (this.bodyCache.parsedBody) { return this.bodyCache.parsedBody as T } const parsedBody = await parseBody<T>(this, options) this.bodyCache.parsedBody = parsedBody return parsedBody }
private cachedBody = (key: keyof Body) => { const { bodyCache, raw } = this const cachedBody = bodyCache[key]
if (cachedBody) { return cachedBody }
if (!bodyCache[key]) { for (const keyOfBodyCache of Object.keys(bodyCache)) { if (keyOfBodyCache === 'parsedBody') { continue } return (async () => { // @ts-expect-error bodyCache[keyOfBodyCache] can be passed as a body let body = await bodyCache[keyOfBodyCache] if (keyOfBodyCache === 'json') { body = JSON.stringify(body) } return await new Response(body)[key]() })() } }
return (bodyCache[key] = raw[key]()) }
/** * `.json()` can parse Request body of type `application/json` * @example * ```ts * app.post('/entry', async (c) => { * const body = await c.req.json() * }) * ``` * @see https://hono.dev/api/request#json */ json<T = any>(): Promise<T> { return this.cachedBody('json') }
/** * `.text()` can parse Request body of type `text/plain` * @example * ```ts * app.post('/entry', async (c) => { * const body = await c.req.text() * }) * ``` * @see https://hono.dev/api/request#text */ text(): Promise<string> { return this.cachedBody('text') }
/** * `.arrayBuffer()` parse Request body as an `ArrayBuffer` * @example * ```ts * app.post('/entry', async (c) => { * const body = await c.req.arrayBuffer() * }) * ``` * @see https://hono.dev/api/request#arraybuffer */ arrayBuffer(): Promise<ArrayBuffer> { return this.cachedBody('arrayBuffer') }
blob(): Promise<Blob> { return this.cachedBody('blob') }
formData(): Promise<FormData> { return this.cachedBody('formData') }
addValidatedData(target: keyof ValidationTargets, data: {}) { this.#validatedData[target] = data }
valid<T extends keyof I & keyof ValidationTargets>(target: T): InputToDataByTarget<I, T> valid(target: keyof ValidationTargets) { return this.#validatedData[target] as unknown }
/** * `.url()` can get the request url strings. * @example * ```ts * app.get('/about/me', (c) => { * const url = c.req.url // `http://localhost:8787/about/me` * ... * }) * ``` * @see https://hono.dev/api/request#url */ get url() { return this.raw.url }
/** * `.method()` can get the method name of the request. * @example * ```ts * app.get('/about/me', (c) => { * const method = c.req.method // `GET` * }) * ``` * @see https://hono.dev/api/request#method */ get method() { return this.raw.method }
/** * `.matchedRoutes()` can return a matched route in the handler * @example * ```ts * app.use('*', async function logger(c, next) { * await next() * c.req.matchedRoutes.forEach(({ handler, method, path }, i) => { * const name = handler.name || (handler.length < 2 ? '[handler]' : '[middleware]') * console.log( * method, * ' ', * path, * ' '.repeat(Math.max(10 - path.length, 0)), * name, * i === c.req.routeIndex ? '<- respond from here' : '' * ) * }) * }) * ``` * @see https://hono.dev/api/request#matchedroutes */ get matchedRoutes(): RouterRoute[] { return this.#matchResult[0].map(([[, route]]) => route) }
/** * `routePath()` can retrieve the path registered within the handler * @example * ```ts * app.get('/posts/:id', (c) => { * return c.json({ path: c.req.routePath }) * }) * ``` * @see https://hono.dev/api/request#routepath */ get routePath(): string { return this.#matchResult[0].map(([[, route]]) => route)[this.routeIndex].path }}
hono

Version Info

Tagged at
a week ago