-
Notifications
You must be signed in to change notification settings - Fork 170
/
api.ts
104 lines (84 loc) · 2.33 KB
/
api.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
import type { ServerRequest } from '../deps.ts'
import type { APIRequest, APIResponse } from '../types.ts'
export class PostAPIRequest implements APIRequest {
#req: ServerRequest
cookies: ReadonlyMap<string, string>
params: ReadonlyMap<string, string>
query: URLSearchParams
constructor(req: ServerRequest, params: Record<string, string>, query: URLSearchParams) {
this.#req = req
const paramsMap = new Map<string, string>()
for (const key in params) {
paramsMap.set(key, params[key])
}
this.params = paramsMap
this.cookies = new Map()
// todo: parse cookies
this.query = query
}
get url(): string {
return this.#req.url
}
get method(): string {
return this.#req.method
}
get proto(): string {
return this.#req.proto
}
get protoMinor(): number {
return this.#req.protoMinor
}
get protoMajor(): number {
return this.#req.protoMajor
}
get headers(): Headers {
return this.#req.headers
}
}
export class PostAPIResponse implements APIResponse {
#req: ServerRequest
#headers: Headers
#status: number
constructor(req: ServerRequest) {
this.#req = req
this.#headers = new Headers()
this.#status = 200
}
status(code: number): this {
this.#status = code
return this
}
addHeader(key: string, value: string): this {
this.#headers.append(key, value)
return this
}
setHeader(key: string, value: string): this {
this.#headers.set(key, value)
return this
}
removeHeader(key: string): this {
this.#headers.delete(key)
return this
}
send(data: string | Uint8Array | ArrayBuffer) {
let body: string | Uint8Array
if (data instanceof ArrayBuffer) {
body = new Uint8Array(data)
} else {
body = data
}
return this.#req.respond({
status: this.#status,
headers: this.#headers,
body
})
}
json(data: any) {
this.#headers.set('Content-Type', 'application/json')
return this.#req.respond({
status: this.#status,
headers: this.#headers,
body: JSON.stringify(data)
})
}
}