-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathresponse.ts
68 lines (64 loc) · 1.67 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
import { Req, Res } from "./model.ts";
import { contentType, extname, join, Status, STATUS_TEXT } from "./deps.ts";
import { decoder } from "./request.ts";
import { parseResponseBody } from "./utils/parse/body.ts";
import { Cookie } from "./cookie.ts";
export class Response {
static createResponse() {
return {
response: {
headers: new Headers(),
},
body: null,
headers: new Headers(),
status: Status.NotFound,
done: false,
redirect: this.redirect,
render: this.render,
cookies: new Cookie(),
send,
};
}
static async render(res: Res, path: string) {
const v = decoder.decode(await Deno.readFile(join(Deno.cwd(), path)));
const cType = contentType(extname(path)) || "text/plain; charset=utf-8";
try {
res.body = v;
res.headers.set("Content-Type", cType);
res.status = Status.OK;
} catch (e) {
console.log(e);
res.status = Status.InternalServerError;
res.body = STATUS_TEXT.get(Status.InternalServerError) as string;
}
}
static redirect(res: Res, url: string) {
res.status = Status.Found;
res.headers.set("Location", url);
}
}
export function send(req: Req, res: Res) {
if (res.done) return;
const request = req.request;
const {
response,
body,
headers = new Headers(),
status = Status.OK,
cookies,
} = res;
try {
if (body) {
parseResponseBody(res);
} else {
response.body = undefined;
}
res.done = true;
cookies.getCookies().forEach((value) => {
headers.set("Set-Cookie", value);
});
request.respond({ ...response, headers, status });
} catch (e) {
console.log(e);
}
}