This repository has been archived by the owner on Jun 27, 2024. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
request_context.ts
372 lines (314 loc) · 8.6 KB
/
request_context.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
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
// Copyright 2023 Samuel Kopp. All rights reserved. Apache-2.0 license.
import {
deadline as resolveWithDeadline,
DeadlineError,
} from 'std/async/deadline.ts'
import { z, ZodStringDef, ZodType, ZodUnionDef } from 'zod'
import { Method } from './base.ts'
import { BaseType, ObjectType } from './handler.ts'
import { AppContext, Context } from './mod.ts'
type Static<T extends ZodType> = T extends ZodType ? z.infer<T>
: never
export class RequestContext<
Params extends Record<string, unknown> = Record<string, never>,
ValidatedBody extends ZodType = never,
ValidatedCookies extends ObjectType = never,
ValidatedHeaders extends ObjectType = never,
ValidatedQuery extends ObjectType = never,
> {
#c: Record<string, string | undefined> | undefined
#h: Record<string, string | undefined> | undefined
#a: AppContext
#p
#q: Record<string, unknown> | undefined
#r
#s
#e
constructor(
a: AppContext,
p: Record<string, string | undefined>,
r: Request,
s: {
body?: ZodType | undefined
cookies?: ObjectType | undefined
headers?: ObjectType | undefined
query?: ObjectType | undefined
params?: Record<string, ZodType>
[key: string]: unknown
} | null,
e: Context['exception'],
) {
this.#a = a
this.#p = p
this.#r = r
this.#s = s
this.#e = e
}
get gateway(): number {
return this.#a.gateway ?? -1
}
get ip(): string {
return this.#a.ip
}
/**
* The method of the incoming request.
*
* @example 'GET'
* @since v0.12
*/
get method() {
return this.#r.method as Uppercase<Method>
}
/**
* A method to retrieve the corresponding value of a parameter.
*/
param<T extends keyof Params>(name: T): Params[T] {
if (this.#s?.params && this.#s.params[name as string]) {
const result = this.#s.params[name as string].safeParse(this.#p[name])
if (!result.success) {
throw this.#e('Bad Request')
}
return result.data as Params[T]
} else {
return this.#p[name as string] as Params[T]
}
}
/**
* Retrieve the original request object.
*
* @since v1.0
*/
get raw() {
return this.#r
}
/**
* The validated body of the incoming request.
*/
async body(options?: {
/**
* This enables the conversion of a FormData request body into a JSON object (if the request body has the MIME type `multipart/form-data`).
*
* @default false
*/
transform: boolean
}): Promise<
[ValidatedBody] extends [never] ? unknown : Static<ValidatedBody>
> {
if (!this.#s?.body) {
// @ts-ignore:
return undefined
}
let body
try {
if (
(this.#s.body as BaseType<ZodStringDef>)._def.typeName ===
'ZodString' ||
(this.#s.body as BaseType<ZodUnionDef>)._def.typeName === 'ZodUnion' &&
(this.#s.body as BaseType<ZodUnionDef>)._def.options.every((
{ _def },
) => _def.typeName === 'ZodString')
) {
body = await resolveWithDeadline(this.#r.text(), 2500)
} else {
if (
(options?.transform === true || this.#s?.transform === true) &&
this.#r.headers.get('content-type') === 'multipart/form-data'
) {
const formData = await resolveWithDeadline(this.#r.formData(), 2500)
body = {} as Record<string, unknown>
for (const [key, value] of formData.entries()) {
body[key] = value
}
} else {
body = await resolveWithDeadline(this.#r.json(), 2500)
}
}
} catch (err: unknown) {
throw this.#e(
err instanceof DeadlineError ? 'Content Too Large' : 'Bad Request',
)
}
const result = this.#s.body.safeParse(body)
if (!result.success) {
throw this.#e('Bad Request')
}
return result.data
}
/**
* The validated cookies of the incoming request.
*/
get cookies(): [ValidatedCookies] extends [never] ? never
: Static<ValidatedCookies> {
if (this.#c || !this.#s?.cookies) {
return this.#c as [ValidatedCookies] extends [never] ? never
: Static<ValidatedCookies>
}
try {
const header = this.#r.headers.get('cookies') ?? ''
if (header.length > 1000) {
throw this.#e('Content Too Large')
}
this.#c = header
.split(/;\s*/)
.map((pair) => pair.split(/=(.+)/))
.reduce((acc: Record<string, string>, [k, v]) => {
acc[k] = v
return acc
}, {})
delete this.#c['']
} catch (_err) {
this.#c = {}
}
const isValid = this.#s.cookies.safeParse(this.#c).success
if (!isValid) {
throw this.#e('Bad Request')
}
return this.#c as [ValidatedCookies] extends [never] ? never
: Static<ValidatedCookies>
}
/**
* The validated headers of the incoming request.
*/
get headers(): [ValidatedHeaders] extends [never]
? Record<string, string | undefined>
: Static<ValidatedHeaders> {
if (this.#h) {
return this.#h as [ValidatedHeaders] extends [never]
? Record<string, string | undefined>
: Static<ValidatedHeaders>
}
this.#h = {}
let num = 0
for (const [key, value] of this.#r.headers) {
if (num === 50) {
break
}
if (!this.#h[key.toLowerCase()]) {
this.#h[key.toLowerCase()] = value
}
num++
}
if (this.#s?.headers) {
const isValid = this.#s.headers.safeParse(this.#h).success
if (!isValid) {
throw this.#e('Bad Request')
}
}
return this.#h as [ValidatedHeaders] extends [never]
? Record<string, string | undefined>
: Static<ValidatedHeaders>
}
/**
* The validated query parameters of the incoming request.
*/
get query(): [ValidatedQuery] extends [never] ? Record<string, unknown>
: Static<ValidatedQuery> {
if (this.#q) {
return this.#q as [ValidatedQuery] extends [never]
? Record<string, unknown>
: Static<ValidatedQuery>
}
this.#q = {}
if (this.#a.request.querystring) {
const arr = this.#a.request.querystring.split('&')
for (let i = 0; i < arr.length; i++) {
const [key, value] = arr[i].split('=')
if (!key) {
continue
}
if (typeof value === 'undefined') {
this.#q[key] = true
continue
}
try {
this.#q[key] = JSON.parse(decodeURIComponent(value))
} catch (_err) {
this.#q[key] = decodeURIComponent(value)
}
}
}
if (this.#s?.query) {
const isValid = this.#s.query.safeParse(this.#q).success
if (!isValid) {
throw this.#e('Bad Request')
}
}
return this.#q as [ValidatedQuery] extends [never] ? Record<string, unknown>
: Static<ValidatedQuery>
}
/**
* Parse the request body as an `ArrayBuffer` with a set time limit in ms.
*
* @param deadline (default `2500`)
*/
async blob(deadline = 2500) {
try {
const promise = this.#r.blob()
return await resolveWithDeadline(promise, deadline)
} catch (_err) {
return null
}
}
/**
* Parse the request body as an `ArrayBuffer` with a set time limit in ms.
*
* @param deadline (default `2500`)
*/
async buffer(deadline = 2500) {
try {
const promise = this.#r.arrayBuffer()
return await resolveWithDeadline(promise, deadline)
} catch (_err) {
return null
}
}
/**
* Parse the request body as JSON with a set time limit in ms.
*
* **If you have defined a validation schema, use `c.req.body()` instead!**
*
* @param deadline (default `2500`)
*/
async json(deadline = 2500): Promise<unknown> {
try {
const promise = this.#r.json()
return await resolveWithDeadline(promise, deadline)
} catch (_err) {
return null
}
}
/**
* Parse the request body as a `FormData` object with a set time limit in ms.
*
* @param deadline (default `2500`)
*/
async formData(deadline = 2500) {
try {
const promise = this.#r.formData()
return await resolveWithDeadline(promise, deadline)
} catch (_err) {
return null
}
}
/**
* Parse the request body as a `string` with a set time limit in ms.
*
* **If you have defined a validation schema, use `c.req.body()` instead!**
*
* @param deadline (default `2500`)
*/
async text(deadline = 2500) {
try {
const promise = this.#r.text()
return await resolveWithDeadline(promise, deadline)
} catch (_err) {
return null
}
}
/**
* A readable stream of the request body.
*/
get stream() {
return this.#r.body
}
}