-
Notifications
You must be signed in to change notification settings - Fork 0
/
router.js
68 lines (54 loc) · 1.46 KB
/
router.js
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
const {parse} = require('url');
const route = require('path-match')();
class Router {
constructor() {
this.routes = new Map();
}
get(path, handler) {
this.add('GET', path, handler);
}
post(path, handler) {
this.add('GET', path, handler);
}
add(method, path, handler) {
if (typeof method !== 'string') {
throw new TypeError('`method` is required!');
}
if (typeof path !== 'string') {
throw new TypeError('`path` is required!');
}
if (typeof handler !== 'function') {
throw new TypeError('`handler` is required!');
}
const routes = this.routes.get(method) || new Set();
routes.add({
match: route(path),
handler
});
this.routes.set(method, routes);
}
match(req, res, { json }) {
const routes = this.routes.get(req.method);
if (!routes) {
return;
}
const {pathname, query} = parse(req.url, true);
for (const r of routes) {
const params = r.match(pathname);
if (params) {
return async () => {
req.params = params;
req.query = query;
if (['POST', 'PUT', 'DELETE', 'PATCH'].indexOf(req.method) >= 0 &&
req.headers['content-type'].startsWith('application/json') &&
typeof json === 'function') {
// we only support json
req.body = await json(req);
}
return r.handler(req, res);
}
}
}
}
}
module.exports = new Router();