-
Notifications
You must be signed in to change notification settings - Fork 17
/
mod.ts
242 lines (216 loc) · 6.56 KB
/
mod.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
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
const { listen, stat, open, readAll } = Deno;
import {
Server,
ServerRequest,
} from "./vendor/https/deno.land/std/http/server.ts";
import { processResponse, Response } from "./response.ts";
import { ErrorCode, getErrorMessage } from "./errors.ts";
import { Handler, HandlerConfig, Method } from "./handler.ts";
import { Params, parseURLSearchParams } from "./params.ts";
import { defaultPort } from "./constants.ts";
import { detectedContentType } from "./mime.ts";
import { ReadCloser } from "./io.ts";
export { contentType, detectedContentType } from "./mime.ts";
export {
del,
get,
link,
options,
patch,
post,
put,
unlink,
} from "./handler.ts";
export { redirect } from "./helpers.ts";
export type { Response } from "./response.ts";
type HandlerMap = Map<string, Map<string, Handler>>; // Map<method, Map<path, handler>>
export function app(...handlerConfigs: HandlerConfig[]): App {
const a = new App(defaultPort);
a.register(...handlerConfigs);
a.serve();
return a;
}
export class App {
private handlerMap: HandlerMap = new Map();
private server!: Server;
constructor(
public readonly port = defaultPort,
public readonly staticEnabled = true,
public readonly publicDir = "public",
) {
for (const method in Method) {
this.handlerMap.set(method, new Map());
}
}
// respondStatic returns Response with static file gotten from a path. If a given path didn't match, this method returns null.
private async respondStatic(path: string): Promise<Response | null> {
let fileInfo: Deno.FileInfo | null = null;
let staticFilePath = `${this.publicDir}${path}`;
try {
fileInfo = await stat(staticFilePath);
} catch (e) {
// Do nothing here.
}
if (fileInfo && fileInfo.isDirectory) {
staticFilePath += "/index.html";
try {
fileInfo = await stat(staticFilePath);
} catch (e) {
fileInfo = null; // FileInfo is not needed any more.
}
}
if (!fileInfo || !fileInfo.isFile) {
return null;
}
return [
200,
{
"Content-Length": fileInfo.size.toString(),
...detectedContentType(staticFilePath),
},
await open(staticFilePath),
];
}
// respond returns Response with from informations of Request.
private async respond(
path: string,
search: string,
method: Method,
req: ServerRequest,
): Promise<Response | null> {
const map = this.handlerMap.get(method);
if (!map) {
return null;
}
const params: Params = {};
let handler;
const REGEX_URI_MATCHES = /(:[^/]+)/g;
const REGEX_URI_REPLACEMENT = "([^/]+)";
const URI_PARAM_MARKER = ":";
Array.from(map.keys()).forEach((endpoint) => {
if (endpoint.indexOf(URI_PARAM_MARKER) !== -1) {
const matcher = endpoint.replace(
REGEX_URI_MATCHES,
REGEX_URI_REPLACEMENT,
);
const matches = path.match(`^${matcher}$`);
if (matches === null) {
return null;
}
const names = endpoint
.match(REGEX_URI_MATCHES)!
.map((name) => name.replace(URI_PARAM_MARKER, ""));
matches.slice(1).forEach((m, i) => {
params[names[i]] = m;
});
handler = map.get(endpoint);
}
});
if (!handler) {
handler = map.get(path);
}
if (!handler) {
return null;
}
if (method === Method.GET) {
if (search) {
Object.assign(params, parseURLSearchParams(search));
}
} else {
const rawContentType = req.headers.get("content-type") ||
"application/octet-stream";
const [contentType, ...typeParamsArray] = rawContentType
.split(";")
.map((s) => s.trim());
const typeParams = typeParamsArray.reduce((params, curr) => {
const [key, value] = curr.split("=");
params[key] = value;
return params;
}, {} as { [key: string]: string });
const decoder = new TextDecoder(typeParams["charset"] || "utf-8"); // TODO: downcase `charset` key
const decodedBody = decoder.decode(await readAll(req.body));
switch (contentType) {
case "application/x-www-form-urlencoded":
Object.assign(params, parseURLSearchParams(decodedBody));
break;
case "application/json":
let obj: Object;
try {
obj = JSON.parse(decodedBody);
} catch (e) {
throw ErrorCode.BadRequest;
}
Object.assign(params, obj);
break;
case "application/octet-stream":
// FIXME: we skip here for now, it should be implemented when Issue #41 resolved.
break;
}
}
const ctx = { path, method, params };
const res = handler(ctx);
if (res instanceof Promise) {
return await (res as Promise<Response>);
}
return res;
}
// Deprecated
public handle = (...args: HandlerConfig[]) => {
console.error("handle is deprecated. Please use register instead of this.");
this.register(...args);
};
public register(...handlerConfigs: HandlerConfig[]) {
for (const { path, method, handler } of handlerConfigs) {
this.handlerMap.get(method)!.set(path, handler);
}
}
public unregister(path: string, method: Method) {
this.handlerMap.get(method)!.delete(path);
}
public async serve() {
const hostname = "0.0.0.0";
const listener = listen({ hostname, port: this.port });
console.log(`listening on http://${hostname}:${this.port}/`);
this.server = new Server(listener);
for await (const req of this.server) {
const method = req.method as Method;
let r: Response | undefined;
if (!req.url) {
throw ErrorCode.NotFound;
}
const [path, search] = req.url.split(/\?(.+)/);
try {
r = (await this.respond(path, search, method, req)) ||
(this.staticEnabled && (await this.respondStatic(path))) ||
undefined;
if (!r) {
throw ErrorCode.NotFound;
}
} catch (err) {
let status = ErrorCode.InternalServerError;
if (typeof err === "number") {
status = err;
} else {
console.error(err);
}
r = [status, getErrorMessage(status)];
}
const res = processResponse(r);
await req.respond(res);
if (isReadCloser(res.body)) {
res.body.close();
}
}
}
public close() {
this.server.close();
}
}
function isReadCloser(obj: any): obj is ReadCloser {
const o = obj as ReadCloser;
return (
typeof o === "object" &&
typeof o.read === "function" &&
typeof o.close === "function"
);
}