-
Notifications
You must be signed in to change notification settings - Fork 3
/
response.ts
66 lines (57 loc) · 1.51 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
import { Response as DenoResponse } from './dependencies.ts';
import { Request } from './request.ts';
import { Header, HeaderManager } from './header.ts';
export class Response {
protected req: Request;
protected body?: string;
protected _status?: number;
protected headerManager: HeaderManager = new HeaderManager();
constructor(req: Request) {
this.req = req;
this._status = 200;
}
addHeader(key: string, value: string) {
this.headerManager.add(key, value);
return this;
}
getHeaders() {
return this.headerManager.parsedHeader;
}
status(_status: number) {
this._status = _status;
return this;
}
getStatus() {
return this._status;
}
protected bodyStringify(body: any) {
switch(typeof body) {
case 'object':
body = JSON.stringify(body);
break;
case 'number':
body = `${body}`;
break;
}
return body;
}
send(body: string) {
body = this.bodyStringify(body);
if(!this.headerManager.has('Content-Type')) {
this.headerManager.add('Content-Type', 'text/html');
}
const res: DenoResponse = {
body,
headers: new Headers(this.headerManager.parsedHeader),
};
this.req.respond(res);
}
json(body: any | string) {
this.headerManager.add('Content-Type', 'application/json');
const res: DenoResponse = {
body: typeof body === 'string' ? body : JSON.stringify(body),
headers: new Headers(this.headerManager.parsedHeader),
};
this.req.respond(res);
}
}