-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrouter.js
72 lines (55 loc) · 1.54 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
69
70
71
72
"use strict";
const url = require("url");
class Router {
constructor () {
this.routes = {
GET: {},
POST: {},
PUT: {},
DELETE: {}
};
this.middlewares = [];
}
setHandler (method, route, cb) {
if (typeof route === "function") {
cb = route;
route = method;
method = "GET";
}
this.routes[method][route] = cb;
}
handle (req, res) {
let urlInfo = url.parse(req.url, true);
let pathname = urlInfo.pathname;
let method = req.method;
let route = this.routes[method][pathname];
// pass along query params
req.query = urlInfo.query;
req.pathname = pathname;
if (route === void 0) {
res.writeHead(404);
return res.end();
} else if (this.middlewares.length > 0) {
let mws = this.middlewares;
let _i = 0;
mws[_i](req, res, next);
// this is tricky. we have to allow for async middleware, but the
// middleware must also process in order
function next () {
if (++_i < mws.length)
mws[_i](req, res, next);
else
return final(req, res);
}
function final (req, res) {
route(req, res);
}
} else {
return route(req, res);
}
}
use (cb) {
this.middlewares.push(cb);
}
}
module.exports = Router;