forked from antitoxic/node-reversable-router
-
Notifications
You must be signed in to change notification settings - Fork 12
/
router.js
336 lines (300 loc) · 9.83 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
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
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
var Route = require('./route');
exports = module.exports = Router;
/**
* Initialize a new `Router` with the given `options`.
*
* @param {Object} options
* @api private
*/
function Router(options) {
var self = this;
options = options || {};
this.expressMode = false;
this.routesByMethod = {};
this.routesByMethodAndPath = {};
this.routesByNameAndMethod = {};
this.callbacksByPathAndMethod = {};
this.parameterCallbackWrappers = [];
this.callbacksPerParameter = {};
// Alias for `dispatch()` to match the express.js concept
this.middleware = function router(req, res, next) {
self.dispatch(req, res, next);
};
this.caseSensitive = options.caseSensitive == undefined ? false : options.caseSensitive;
}
/**
* Find matching route
*
* @param req
* @return {boolean|Object}
*/
Router.prototype.match = function (req) {
var method = req.method.toLowerCase();
var routes = this.routesByMethod[method];
if (!routes) return false;
var offset = req.route == undefined ? 0 : routes.indexOf(req.route) + 1;
// Performance: Lazy matching. Only match 1 route at a time. Most often the first route will generate the server response
for (var i = offset; i < routes.length; i++) {
var route = routes[i];
var outcome = route.match(req.path);
if (outcome === false) continue;
// guarantee array of parameters
outcome = outcome === true ? [] : outcome;
return {
route: route,
callbacks:this.callbacksByPathAndMethod[route.path][method],
params: outcome
}
}
return false;
}
/**
* Registers new route
* @param method
* @param path
* @param callbacks
* @param options
*/
Router.prototype.add = function (method, path, callbacks, options) {
function flatten(arr, ret) {
var ret = ret || []
, len = arr.length;
for (var i = 0; i < len; ++i) {
if (Array.isArray(arr[i])) {
flatten(arr[i], ret);
} else {
ret.push(arr[i]);
}
}
return ret;
}
callbacks = [callbacks]
method = method.toLowerCase();
options = options || {};
this.routesByMethodAndPath[method] = this.routesByMethodAndPath[method] || {};
options.caseSensitive = options.caseSensitive == undefined ? this.caseSensitive : options.caseSensitive;
if (this.routesByMethodAndPath[method][path] == undefined) {
var route = new Route(path, options);
route.__defineGetter__('name', function() {return this.options.name});
if (this.expressMode) {
route.generate = expressGenerateRoute(require("path-to-regexp").compile(path));
}
this.routesByMethod[method] = this.routesByMethod[method] || [];
this.routesByMethod[method].push(route);
this.routesByMethodAndPath[method][path] = route;
if (options.name != undefined) {
this.routesByNameAndMethod[options.name] = this.routesByNameAndMethod[options.name] || {};
this.routesByNameAndMethod[options.name][method] = route;
}
} else {
this.routesByMethodAndPath[method][path].setOptions(options);
}
this.callbacksByPathAndMethod[path] = this.callbacksByPathAndMethod[path] || {};
this.callbacksByPathAndMethod[path][method] = flatten(callbacks);
}
var expressGenerateRoute = function(compile) {
return function(userParams) {
var foundAtLeastOneNull = false;
if (userParams) {
var keys = Object.keys(userParams);
for (var i = 0; i < keys.length; i++) {
if (userParams[keys[i]] === null) {
userParams[keys[i]] = "__NULL_PLACEHOLDER__";
foundAtLeastOneNull = true;
}
}
}
var routeName = compile(userParams);
if (!foundAtLeastOneNull) return routeName;
for (var i = 0; i < keys.length; i++) {
if (userParams[keys[i]] === "__NULL_PLACEHOLDER__") {
userParams[keys[i]] = null;
}
}
return routeName.replace(/\/__NULL_PLACEHOLDER__/g, "");
}
}
/**
* Builds a URL based on the route name, method and parameters provided
*
* @param name
* @param params
* @param method
* @return {String}
*/
Router.prototype.build = function (name, params, method) {
if (this.routesByNameAndMethod[name] == undefined) throw new Error('No route found with the name:' + name);
var possibleRoutes = this.routesByNameAndMethod[name];
method = method || Object.keys(possibleRoutes)[0];
return possibleRoutes[method].generate(params);
}
/**
* Register template helper functions with exress.js application
* @param app
* @return Router
*/
Router.prototype.registerAppHelpers = function (app) {
var self = this;
var helperName = 'url';
if (app.helpers) {
var helpers = {};
helpers[helperName] = function(name, params, method) { return self.build(name, params, method)};
app.helpers(helpers);
} else {
app.locals[helperName] = function(name, params, method) { return self.build(name, params, method)};
}
return this;
}
/**
* Register a param callback `callback` for the given parameter `name`.
*
* @param {String|Function} name
* @param {Function} callback
* @return {*|Router} for chaining
* @api public
*/
Router.prototype.param = function (name, callback) {
// No name passed, add a modifier
if ('function' == typeof name) {
this.parameterCallbackWrappers.push(name);
return;
}
// apply param functions
var callbackWrappers = this.parameterCallbackWrappers;
var modifiedCallback;
callbackWrappers.forEach(function (wrapper) {
if (modifiedCallback = wrapper(name, callback)) {
callback = modifiedCallback;
}
});
// ensure we end up with a
// middleware function
if (typeof callback != 'function') {
throw new Error('invalid callback call for `' + name + '`, got ' + callback);
}
(this.callbacksPerParameter[name] = this.callbacksPerParameter[name] || []).push(callback);
return this;
};
/**
* Chainable routing dispatch
* (analogous to express middeware concept)
*
* @param req
* @param res
* @param next
*/
Router.prototype.dispatch = function (req, res, next) {
var self = this;
var callbacksPerParameter = this.callbacksPerParameter;
nextRoute();
function nextRoute(err) {
// match route
var match = self.match(req);
if (match == false) return next(err);
req.route = match.route;
req.params = match.params;
// workaround vars for the recursion
var i = 0;
var paramIndex = 0;
var paramCallbackIndex;
var parameterNames = Object.keys(req.params);
var paramValue;
var paramName;
var paramCallbacks;
//Start the execution chain. Process parameters, next invoke route middleware callbacks
processNextParameter();
// Callbacks for each parameter
// We need this to be recursive rather then a loop in order to allow the fluid `next()` concept from the actual callbacks
function processNextParameter(err) {
paramCallbackIndex = 0;
paramName = parameterNames[paramIndex++];
paramValue = paramName && req.params[paramName];
paramCallbacks = paramName && callbacksPerParameter[paramName];
try {
if ('route' == err) {
// Specific case where the error means `next route please`? Strange, anyways this is inherited by express.js
nextRoute();
} else if (err) {
// Handle errors. Assumption is made that there's a global error handler or a specific route callback that handle the errors
nextRouteMiddleware(err);
} else if (paramCallbacks) {
// No errors so just run through the parameter callbacks if there's any
nextCallbackForParam();
} else if (paramName) {
// No callbacks
processNextParameter();
} else {
// Parameter callbacks ended, start running route middleware callbacks
nextRouteMiddleware();
}
} catch (err) {
processNextParameter(err);
}
}
// single param callbacks
function nextCallbackForParam(err) {
var callback = paramCallbacks[paramCallbackIndex++];
if (err || !callback) return processNextParameter(err);
callback(req, res, nextCallbackForParam, paramValue, paramName);
}
// invoke route callbacks
function nextRouteMiddleware(err) {
var callback = match.callbacks[i++];
try {
if ('route' == err) {
// Specific case where the error means `next route please`? Strange.. anyways this is inherited by express.js
nextRoute();
} else if (err && callback) {
// Handle errors. If the current callback doesn't support error handling try next one
if (callback.length < 4) return nextRouteMiddleware(err);
callback(err, req, res, nextRouteMiddleware);
} else if (callback) {
callback(req, res, nextRouteMiddleware);
} else {
// No more callbacks
nextRoute(err);
}
} catch (err) {
nextRouteMiddleware(err);
}
}
}
};
/**
* Extend express.js application
* @param app
* @return Router
*/
Router.prototype.extendExpress = function (app) {
var methods = require('methods');
this.expressMode = true;
app.namedRoutes = this;
app._routingContext = [];
methods.forEach(function (method) {
var originalMethod = app[method];
app[method] = function (key) {
if ('get' == method && 1 == arguments.length && typeof key == 'string') return this.set(key);
var args = this._routingContext.concat([].slice.call(arguments));
var path = args[0];
var name = "";
// Check if second argument is the route name
if (typeof args[1] == 'string') {
name = args[1];
args[1] = function(req, res, next){
req.route.name = name;
next();
};
}
this.namedRoutes.add(method, path, [], {name: name});
return originalMethod.apply(this, args);
}
});
app.all = function() {
var methods = require('methods');
var args = [].slice.call(arguments);
return methods.forEach(function(method){
app[method].apply(app, args);
});
};
return this;
}