/
route.js
49 lines (43 loc) · 1.12 KB
/
route.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
function Route(method, regex, middleware, func) {
this.method = method;
if (typeof(regex) === "string") {
regex = new RegExp(regex + "$");
}
this.regex = regex;
if (func) {
this.func = func;
this.setMiddleware(middleware);
} else {
this.func = middleware;
this.setMiddleware([]);
}
}
Route.prototype.setMiddleware = function(middleware) {
if (Array.isArray(middleware)) {
this.middleware = middleware;
} else {
this.middleware = [middleware];
}
}
Route.prototype.didMatch = function(method, path) {
return (method == this.method || !this.method) && this.regex.test(path);
}
Route.prototype.runFunc = function(req, res, path, rudder) {
var args = this.regex.exec(path).slice(1);
args.unshift(res); args.unshift(req);
this.func.apply(rudder, args);
}
Route.prototype.execute = function(req, res, path, rudder) {
var curr = -1,
self = this;
function next() {
curr += 1;
if (curr == self.middleware.length) {
self.runFunc(req, res, path, rudder);
} else {
self.middleware[curr].call(rudder, req, res, next);
}
}
next();
}
module.exports = Route;