-
Notifications
You must be signed in to change notification settings - Fork 170
/
api.ts
180 lines (160 loc) · 5.11 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
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
import type { BufReader, BufWriter } from 'https://deno.land/std@0.90.0/io/bufio.ts'
import type { MultipartFormData } from 'https://deno.land/std@0.90.0/mime/multipart.ts'
import { MultipartReader } from 'https://deno.land/std@0.90.0/mime/multipart.ts'
import { compress as brotli } from 'https://deno.land/x/brotli@v0.1.4/mod.ts'
import { gzipEncode as gzip } from 'https://deno.land/x/wasm_gzip@v1.0.0/mod.ts'
import log from '../shared/log.ts'
import type { APIRequest, ServerRequest, ServerResponse } from '../types.ts'
export class Request implements APIRequest {
#req: ServerRequest
#params: URLSearchParams
#cookies: ReadonlyMap<string, string>
#resp = {
status: 200,
headers: new Headers({
Server: 'Aleph.js',
}),
done: false
}
constructor(req: ServerRequest, params: URLSearchParams) {
this.#req = req
this.#params = params
const cookies = new Map()
this.headers.get('cookie')?.split(';').forEach(cookie => {
const p = cookie.trim().split('=')
if (p.length >= 2) {
cookies.set(p.shift()!.trim(), decodeURI(p.join('=')))
}
})
this.#cookies = cookies
}
get url(): string {
return this.#req.url
}
get method(): string {
return this.#req.method
}
get headers(): Headers {
return this.#req.headers
}
get conn(): Deno.Conn {
return this.#req.conn
}
get r(): BufReader {
return this.#req.r
}
get w(): BufWriter {
return this.#req.w
}
get body(): Deno.Reader {
return this.#req.body
}
async respond(r: ServerResponse): Promise<void> {
return this.#req.respond(r)
}
get params(): URLSearchParams {
return this.#params
}
get cookies(): ReadonlyMap<string, string> {
return this.#cookies
}
async readBody(type?: 'raw'): Promise<Uint8Array>
async readBody(type: 'text'): Promise<string>
async readBody(type: 'json'): Promise<any>
async readBody(type: 'form'): Promise<MultipartFormData>
async readBody(type?: string): Promise<any> {
switch (type) {
case 'text': {
const buff: Uint8Array = await Deno.readAll(this.body)
const encoded = new TextDecoder('utf-8').decode(buff)
return encoded
}
case 'json': {
const buff: Uint8Array = await Deno.readAll(this.body)
const encoded = new TextDecoder('utf-8').decode(buff)
const data = JSON.parse(encoded)
return data
}
case 'form': {
const contentType = this.headers.get('content-type') as string
const reader = new MultipartReader(this.body, contentType)
return reader.readForm()
}
default: {
return await Deno.readAll(this.body)
}
}
}
addHeader(key: string, value: string): this {
this.#resp.headers.append(key, value)
return this
}
setHeader(key: string, value: string): this {
this.#resp.headers.set(key, value)
return this
}
removeHeader(key: string): this {
this.#resp.headers.delete(key)
return this
}
status(code: number): this {
this.#resp.status = code
return this
}
async send(data?: string | Uint8Array | ArrayBuffer, contentType?: string): Promise<void> {
if (this.#resp.done) {
log.warn('ServerRequest: repeat respond calls')
return Promise.resolve()
}
let body = new Uint8Array()
if (typeof data === 'string') {
body = new TextEncoder().encode(data)
} else if (data instanceof Uint8Array) {
body = data
} else if (data instanceof ArrayBuffer) {
body = new Uint8Array(data)
}
if (contentType) {
this.#resp.headers.set('Content-Type', contentType)
} else if (this.#resp.headers.has('Content-Type')) {
contentType = this.#resp.headers.get('Content-Type')!
} else if (typeof data === 'string' && data.length > 0) {
contentType = 'text/plain; charset=utf-8'
}
let shouldCompress = false
if (contentType) {
if (contentType.startsWith('text/')) {
shouldCompress = true
} else if (/^application\/(javascript|typecript|wasm|json|xml)/i.test(contentType)) {
shouldCompress = true
} else if (/^image\/svg+xml/i.test(contentType)) {
shouldCompress = true
}
}
if (shouldCompress && body.length > 1024) {
if (this.headers.get('accept-encoding')?.includes('br')) {
this.#resp.headers.set('Vary', 'Origin')
this.#resp.headers.set('Content-Encoding', 'br')
body = brotli(body)
} else if (this.headers.get('accept-encoding')?.includes('gzip')) {
this.#resp.headers.set('Vary', 'Origin')
this.#resp.headers.set('Content-Encoding', 'gzip')
body = gzip(body)
}
}
this.#resp.headers.set('Date', (new Date).toUTCString())
this.#resp.done = true
try {
await this.respond({
status: this.#resp.status,
headers: this.#resp.headers,
body
})
} catch (err) {
log.warn('ServerRequest.respond:', err.message)
}
}
json(data: any, replacer?: (this: any, key: string, value: any) => any, space?: string | number): Promise<void> {
return this.send(JSON.stringify(data, replacer, space), 'application/json; charset=utf-8')
}
}