forked from zhmushan/abc
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcontext.ts
189 lines (164 loc) · 5.06 KB
/
context.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
181
182
183
184
185
186
187
188
189
import type { Application } from "./app.ts";
import type { ServerRequest, Response } from "./deps.ts";
import type { ContextOptions } from "./types.ts";
import {
Status,
path,
cookie,
MultipartReader,
encode,
decode,
} from "./deps.ts";
import { Header, MIME } from "./constants.ts";
import { contentType, NotFoundHandler } from "./util.ts";
const { cwd, lstat, readFile, readAll } = Deno;
type Cookie = cookie.Cookie;
type Cookies = cookie.Cookies;
export class Context {
app!: Application;
request!: ServerRequest;
url!: URL;
response: Response & { headers: Headers } = { headers: new Headers() };
params: Record<string, string> = {};
customContext: any;
get cookies(): Cookies {
return cookie.getCookies(this.request);
}
get path(): string {
return this.url.pathname;
}
get method(): string {
return this.request.method;
}
get queryParams(): Record<string, string> {
const params: Record<string, string> = {};
for (const [k, v] of this.url.searchParams) {
params[k] = v;
}
return params;
}
constructor(opts: ContextOptions);
constructor(c: Context);
constructor(optionsOrContext: ContextOptions | Context) {
if (optionsOrContext instanceof Context) {
Object.assign(this, optionsOrContext);
this.customContext = this;
return;
}
const opts = optionsOrContext;
this.app = opts.app;
this.request = opts.r;
this.url = new URL(this.request.url, `http://0.0.0.0`);
}
#writeContentType = (v: string): void => {
if (!this.response.headers.has(Header.ContentType)) {
this.response.headers.set(Header.ContentType, v);
}
};
async body<T extends unknown>(): Promise<T> {
const contentType = this.request.headers.get(Header.ContentType);
walk: {
let data: Record<string, unknown> = {};
if (contentType) {
if (contentType.includes(MIME.ApplicationJSON)) {
data = JSON.parse(decode(await readAll(this.request.body)));
} else if (contentType.includes(MIME.ApplicationForm)) {
for (
const [k, v] of new URLSearchParams(
decode(await readAll(this.request.body)),
)
) {
data[k] = v;
}
} else if (contentType.includes(MIME.MultipartForm)) {
const match = contentType.match(/boundary=([^\s]+)/);
const boundary = match ? match[1] : undefined;
if (boundary) {
const mr = new MultipartReader(this.request.body, boundary);
const form = await mr.readForm();
for (const [k, v] of form.entries()) {
data[k] = v;
}
}
} else {
break walk;
}
} else {
break walk;
}
return data as T;
}
return decode(await readAll(this.request.body)) as T;
}
string(v: string, code: Status = Status.OK): void {
this.#writeContentType(MIME.TextPlain);
this.response.status = code;
this.response.body = encode(v);
}
json(v: Record<string, any> | string, code: Status = Status.OK): void {
this.#writeContentType(MIME.ApplicationJSON);
this.response.status = code;
this.response.body = encode(typeof v === "object" ? JSON.stringify(v) : v);
}
/** Sends an HTTP response with status code. */
html(v: string, code: Status = Status.OK): void {
this.#writeContentType(MIME.TextHTML);
this.response.status = code;
this.response.body = encode(v);
}
/** Sends an HTTP blob response with status code. */
htmlBlob(b: Uint8Array | Deno.Reader, code: Status = Status.OK): void {
this.blob(b, MIME.TextHTML, code);
}
/**
* Renders a template with data and sends a text/html response with status code.
* renderer must be registered first.
*/
async render<T>(
name: string,
data: T = {} as T,
code: Status = Status.OK,
): Promise<void> {
if (!this.app.renderer) {
throw new Error();
}
const r = await this.app.renderer.render(name, data);
this.htmlBlob(r, code);
}
/** Sends a blob response with content type and status code. */
blob(
b: Uint8Array | Deno.Reader,
contentType?: string,
code: Status = Status.OK,
): void {
if (contentType) {
this.#writeContentType(contentType);
}
this.response.status = code;
this.response.body = b;
}
async file(filepath: string): Promise<void> {
filepath = path.join(cwd(), filepath);
try {
const fileinfo = await lstat(filepath);
if (
fileinfo.isDirectory &&
(await lstat(filepath + "index.html")).isFile
) {
filepath = path.join(filepath, "index.html");
}
this.blob(await readFile(filepath), contentType(filepath));
} catch {
NotFoundHandler();
}
}
/** append a `Set-Cookie` header to the response */
setCookie(c: Cookie): void {
cookie.setCookie(this.response, c);
}
/** Redirects a response to a specific URL. the `code` defaults to `302` if omitted */
redirect(url: string, code = Status.Found): void {
this.response.headers.set(Header.Location, url);
this.response.status = code;
}
}