-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrouter.js
60 lines (51 loc) · 1.59 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
const express = require('express');
app = express();
const AwesomeRouter = function () {
function router(req, res, next) {
return router.handle(req, res, next);
}
router.routes = [];
router.handle = function (req, res, next) {
const handlers = this.routes
.filter((x) => x.method === req.method || x.method === '*')
// in real router the matching is done by regex comparison, here I used a quick workaround
.filter((x) => req.path.startsWith(x.path))
.map((x) => x.handler);
let i = 0;
let shouldContinue = true;
while (i < handlers.length && shouldContinue) {
const handler = handlers[i];
shouldContinue = false;
handler(req, res, () => {
shouldContinue = true;
});
i++;
}
if (next && shouldContinue) next();
};
router.addRoute = function (method, path, handler) {
this.routes.push({method, path, handler});
};
router.use = function (path, handler) {
router.addRoute('*', path, handler);
};
router.post = function (path, handler) {
router.addRoute('POST', path, handler);
};
router.get = function (path, handler) {
router.addRoute('GET', path, handler);
};
return router;
};
const router = AwesomeRouter();
router.use('/', (req, res, next) => {
console.log('logging', req.path);
next();
});
router.get('/hi', (req, res, next) => {
res.send('hi there!');
});
app.use(router);
app.listen(3000, () => {
console.log('listening...');
});