/
request.ts
77 lines (72 loc) · 1.97 KB
/
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
declare global {
interface Request<ParamKeyType extends string = string> {
param: {
(key: ParamKeyType): string
(): Record<ParamKeyType, string>
}
paramData?: Record<ParamKeyType, string>
query: {
(key: string): string
(): Record<string, string>
}
queries: {
(key: string): string[]
(): Record<string, string[]>
}
header: {
(name: string): string
(): Record<string, string>
}
}
}
export function extendRequestPrototype() {
if (!!Request.prototype.param as boolean) {
// already extended
return
}
Request.prototype.param = function (this: Request, key?: string) {
if (this.paramData) {
if (key) {
return this.paramData[key]
} else {
return this.paramData
}
}
return null
} as InstanceType<typeof Request>['param']
Request.prototype.header = function (this: Request, name?: string) {
if (name) {
return this.headers.get(name)
} else {
const result: Record<string, string> = {}
for (const [key, value] of this.headers) {
result[key] = value
}
return result
}
} as InstanceType<typeof Request>['header']
Request.prototype.query = function (this: Request, key?: string) {
const url = new URL(this.url)
if (key) {
return url.searchParams.get(key)
} else {
const result: Record<string, string> = {}
for (const key of url.searchParams.keys()) {
result[key] = url.searchParams.get(key) || ''
}
return result
}
} as InstanceType<typeof Request>['query']
Request.prototype.queries = function (this: Request, key?: string) {
const url = new URL(this.url)
if (key) {
return url.searchParams.getAll(key)
} else {
const result: Record<string, string[]> = {}
for (const key of url.searchParams.keys()) {
result[key] = url.searchParams.getAll(key)
}
return result
}
} as InstanceType<typeof Request>['queries']
}