-
Notifications
You must be signed in to change notification settings - Fork 169
/
response.ts
74 lines (65 loc) · 2.2 KB
/
response.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
import { APIResponse as IResponse } from '../types.d.ts'
import log from '../shared/log.ts'
import compress from './compress.ts'
export class APIResponse implements IResponse {
status = 200
headers = new Headers()
body?: string | Uint8Array | ArrayBuffer | ReadableStream<Uint8Array>
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
}
redirect(url: string, status = 302): this {
this.setHeader('Location', url)
this.status = status
return this
}
json(data: any, space?: string | number): this {
this.setHeader('Content-Type', 'application/json; charset=utf-8')
this.body = JSON.stringify(data, undefined, space)
return this
}
async writeTo({ request, respondWith }: Deno.RequestEvent, status?: number): Promise<void> {
let { body, headers, } = this
let contentType: string | null = null
if (headers.has('Content-Type')) {
contentType = headers.get('Content-Type')!
} else if (typeof body === 'string') {
contentType = 'text/plain; charset=utf-8'
headers.set('Content-Type', contentType)
}
if (!headers.has('Date')) {
headers.set('Date', (new Date).toUTCString())
}
const acceptEncoding = request.headers.get('accept-encoding')
if (acceptEncoding && body && contentType) {
let data = new Uint8Array()
if (typeof body === 'string') {
data = new TextEncoder().encode(body)
} else if (body instanceof Uint8Array) {
data = body
} else if (body instanceof ArrayBuffer) {
data = new Uint8Array(body)
}
const contentEncoding = compress.accept(acceptEncoding, contentType, data.length)
if (contentEncoding) {
body = await compress.compress(data, contentEncoding)
headers.set('Vary', 'Origin')
headers.set('Content-Encoding', contentEncoding)
}
}
try {
await respondWith(new Response(body, { headers, status: status || this.status }))
} catch (err) {
log.warn('http:', err.message)
}
}
}