-
Notifications
You must be signed in to change notification settings - Fork 0
/
router.js
90 lines (74 loc) · 1.69 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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
const http = require("http");
module.exports = class SimpleRouter {
constructor() {
this.stack = [];
this.routes = [];
}
use(middleware) {
if (typeof middleware !== 'function') {
throw new Error('Middleware must be a function!');
}
this.stack.push(middleware);
}
addRoute(method, path, cb) {
if (this.routes.find(r => r.path === path && r.method === method)) return;
this.routes.push({
method,
path,
cb,
});
}
get(path, cb) {
this.addRoute("GET", path, cb);
}
post(path, cb) {
this.addRoute("POST", path, cb);
}
handle(req, res, cb) {
let index = 0;
const next = (err) => {
if (err != null) {
return cb(err);
}
if (index >= this.stack.length) {
return this.route_handle(req, res, cb);
}
const middleware = this.stack[index++];
try {
middleware(req, res, next);
} catch(error) {
next(error);
}
};
next();
}
route_handle(req, res, cb) {
const next = (err) => {
if (err != null) {
return cb(err);
}
const route = this.routes.find(r => r.method === req.method && r.path === req.url);
if (!route) {
res.writeHead(404);
res.end('Page not found');
}
try {
route.cb(req, res, next);
} catch(error) {
next(error);
}
};
next();
}
listen(port, callback) {
const handler = (req, res) => {
this.handle(req, res, err => {
if (err) {
res.writeHead(500);
res.end('Internal Server Error');
}
});
};
return http.createServer(handler).listen({ port }, callback);
}
}