forked from hviana/faster
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.ts
297 lines (281 loc) · 7.14 KB
/
server.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
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
/*
Created by: Henrique Emanoel Viana
Githu: https://github.com/hviana
Page: https://sites.google.com/site/henriqueemanoelviana
cel: +55 (41) 99999-4664
*/
export type Params = {
[key: string]: string;
};
export type ProcessorFunc = (ctx: Context) => Promise<void> | void;
export type ContextResponse = {
body: any;
headers: Headers;
status: number;
statusText: string;
};
export class Context {
#conn: Deno.Conn;
#httpConn: Deno.HttpConn;
#requestEvent: Deno.RequestEvent;
#params: Params;
#url: URL;
req: Request;
body: any = undefined;
#extra: { [key: string]: any } = {};
error: Error | undefined = undefined;
#postProcessors: Set<ProcessorFunc> = new Set();
constructor(
conn: Deno.Conn,
httpConn: Deno.HttpConn,
requestEvent: Deno.RequestEvent,
params: Params,
url: URL,
req: Request,
hasRoute: boolean,
) {
this.#conn = conn;
this.#httpConn = httpConn;
this.#requestEvent = requestEvent;
this.#params = params;
this.#url = url;
this.req = req;
this.res.status = hasRoute ? 200 : 404;
}
res: ContextResponse = {
body: undefined,
headers: new Headers(),
status: 200,
statusText: "",
};
get conn() {
return this.#conn;
}
get httpConn() {
return this.#httpConn;
}
get requestEvent() {
return this.#requestEvent;
}
get params() {
return this.#params;
}
get url() {
return this.#url;
}
get extra() {
return this.#extra;
}
get postProcessors() {
return this.#postProcessors;
}
redirect(url: string) {
this.postProcessors.add((ctx: Context) => {
ctx.res.headers.set("Location", url);
ctx.res.status = 301;
});
}
}
export type NextFunc = () => Promise<void> | void;
// Adapted from https://github.com/lukeed/regexparam/blob/master/src/index.js
export function parse(
str: RegExp | string,
loose?: boolean,
): { keys: string[]; pattern: RegExp } {
if (str instanceof RegExp) return { keys: [], pattern: str };
var c: string,
o: number,
tmp: string | undefined,
ext: number,
keys = [],
pattern: string = "",
arr: string[] = str.split("/");
arr[0] || arr.shift();
while (tmp = arr.shift()) {
c = tmp[0];
if (c === "*") {
keys.push("wild");
pattern += "/(.*)";
} else if (c === ":") {
o = tmp.indexOf("?", 1);
ext = tmp.indexOf(".", 1);
keys.push(tmp.substring(1, !!~o ? o : !!~ext ? ext : tmp.length));
pattern += !!~o && !~ext ? "(?:/([^/]+?))?" : "/([^/]+?)";
if (!!~ext) pattern += (!!~o ? "?" : "") + "\\" + tmp.substring(ext);
} else {
pattern += "/" + tmp;
}
}
return {
keys: keys,
pattern: new RegExp("^" + pattern + (loose ? "(?=$|\/)" : "\/?$"), "i"),
};
}
export type RouteFn = (
ctx: Context,
next: NextFunc,
) => Promise<void> | void;
type RoutePattern = RegExp;
type Method =
| "ALL"
| "GET"
| "POST"
| "HEAD"
| "PATCH"
| "OPTIONS"
| "CONNECT"
| "DELETE"
| "TRACE"
| "POST"
| "PUT";
// A Route is a route when it has a routepattern otherwise it is treated as a middleware.
export type Route = {
pattern?: RoutePattern;
method: Method;
keys: string[];
handlers: RouteFn[];
};
export class Server {
// NOTE: This is transpiled into the constructor, therefore equivalent to this.routes = [];
#routes: Route[] = [];
// NOTE: Using .bind can significantly increase perf compared to arrow functions.
public all = this.#add.bind(this, "ALL");
public get = this.#add.bind(this, "GET");
public head = this.#add.bind(this, "HEAD");
public patch = this.#add.bind(this, "PATCH");
public options = this.#add.bind(this, "OPTIONS");
public connect = this.#add.bind(this, "CONNECT");
public delete = this.#add.bind(this, "DELETE");
public trace = this.#add.bind(this, "TRACE");
public post = this.#add.bind(this, "POST");
public put = this.#add.bind(this, "PUT");
public use(...handlers: RouteFn[]) {
this.#routes.push({
keys: [],
method: "ALL",
handlers,
});
return this;
}
#add(method: Method, route: string | RegExp, ...handlers: RouteFn[]) {
var {
keys,
pattern,
} = parse(route);
this.#routes.push({
keys,
method,
handlers,
pattern,
});
return this;
}
async #middlewareHandler(
fns: RouteFn[],
fnIndex: number,
ctx: Context,
): Promise<void> {
if (fns[fnIndex] !== undefined) {
try {
await fns[fnIndex](
ctx,
async () => await this.#middlewareHandler(fns, fnIndex + 1, ctx),
);
} catch (e) {
ctx.error = e;
}
}
}
async #handleRequest(conn: Deno.Conn) {
try {
const httpConn = Deno.serveHttp(conn);
for await (const requestEvent of httpConn) {
const req = requestEvent.request;
const url = new URL(requestEvent.request.url);
const requestHandlers: RouteFn[] = [];
const params: Params = {};
const len = this.#routes.length;
var hasRoute = false;
for (var i = 0; i < len; i++) {
const r = this.#routes[i];
const keyLength = r.keys.length;
var matches: null | string[] = null;
if (
r.pattern === undefined ||
(req.method === r.method &&
(matches = r.pattern.exec(
url.pathname,
)))
) {
if (r.pattern) {
hasRoute = true;
if (keyLength > 0) {
if (matches) {
var inc = 0;
while (inc < keyLength) {
params[r.keys[inc]] = decodeURIComponent(matches[++inc]);
}
}
}
}
requestHandlers.push(...r.handlers);
}
}
var ctx = new Context(
conn,
httpConn,
requestEvent,
params,
url,
req,
hasRoute,
);
await this.#middlewareHandler(requestHandlers, 0, ctx);
if (!ctx.error) {
try {
for (const p of ctx.postProcessors) {
await p(ctx);
}
} catch (e) {
ctx.error = e;
}
}
if (ctx.error) {
ctx.res.status = 500;
ctx.res.headers.set(
"Content-Type",
"application/json",
);
ctx.res.body = JSON.stringify({
msg: (ctx.error.message || ctx.error),
stack: ctx.error.stack,
});
}
await requestEvent.respondWith(
new Response(ctx.res.body, {
headers: ctx.res.headers,
status: ctx.res.status,
statusText: ctx.res.statusText,
}),
);
}
} catch (e) {
console.log(e);
}
}
public async listen(serverParams: any) {
const server = (serverParams.certFile || serverParams.port === 443)
? Deno.listenTls(serverParams)
: Deno.listen(serverParams);
try {
for await (const conn of server) {
this.#handleRequest(conn);
}
} catch (e) {
console.log(e);
if (e.name === "NotConnected") {
await this.listen(serverParams);
}
}
}
}