-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
150 lines (125 loc) · 2.38 KB
/
index.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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
/*
* router
* Router component
*
* @copyright 2013 Enrico Marino and Federico Spini
* @license MIT
*/
/*
* Expose `Router`
*/
module.exports = Router;
/*
* Component dependencies
*/
var Route = require('route');
var Emitter = require('emitter');
/**
* Utils
*/
var array = [];
var slice = array.slice;
var object = {};
var toString = object.toString;
/*
* Router
* Create a router.
*
* @api public
*/
function Router() {
if (!(this instanceof Router)) {
return new Router();
}
Emitter.call(this);
this.routes = [];
}
/**
* Router.use
* Use a plugin
*
* @param {Function} fn plugin
* @return {Router} Router constructor
* @api public
*/
Router.use = function (fn) {
fn(this);
return this;
};
/**
* route
* add a route
*
* @param {String} path path
* @param {Function} callback... callback
* @return {Route} the route of `path`
* @api public
*/
Router.prototype.get = function (path, callback) {
var routes = this.routes;
var route = new Route(path);
var args = slice.call(arguments);
if (toString.call(callback) === '[object Array]') {
callback = this.waterfall(callback);
} else if (args.length > 2) {
args.shift();
callback = this.waterfall(args);
}
routes.push({
regexp: route,
callback: callback
});
return route;
};
/**
* Dispatch the given `path`,
* matching routes sequentially.
*
* @param {String} path path to dispatch
* @param {Router} this for chaining
* @api public
*/
Router.prototype.dispatch = function (path) {
var routes = this.routes;
var n = routes.length;
var i;
var route;
var regexp;
var callback;
var params;
var req = {};
for (i = 0; i < n; i += 1) {
route = routes[i];
regexp = route.regexp;
callback = route.callback;
params = regexp.match(path);
if (params) {
req.path = path;
req.params = params;
callback.call(null, req);
return this;
}
}
return this;
};
/**
* waterfall
* @api private
*/
Router.prototype.waterfall = function (callbacks) {
var router = this;
return function (req) {
var n = callbacks.length;
var i;
var wrapped = new Array(n);
function wrap (current, next) {
return function () {
current.call(router, req, next);
};
}
for (i = n-1; i >= 0; i -= 1) {
wrapped[i] = wrap(callbacks[i], wrapped[i+1]);
}
wrapped[0](req);
};
};