/
router.js
361 lines (315 loc) · 8.78 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
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
'use strict';
var EventEmitter = require('events').EventEmitter;
var util = require('util');
var http = require('http');
var _ = require('lodash');
var assert = require('assert-plus');
var errors = require('restify-errors');
var FindMyWay = require('find-my-way');
var Chain = require('./chain');
var dtrace = require('./dtrace');
///--- Globals
var MethodNotAllowedError = errors.MethodNotAllowedError;
var ResourceNotFoundError = errors.ResourceNotFoundError;
///--- API
/**
* Router class handles mapping of http verbs and a regexp path,
* to an array of handler functions.
*
* @class
* @public
* @param {Object} options - an options object
* @param {Bunyan} options.log - Bunyan logger instance
* @param {Boolean} [options.strictRouting] - strict routing
*/
function Router(options) {
assert.object(options, 'options');
assert.object(options.log, 'options.log');
EventEmitter.call(this);
this.strict = Boolean(options.strictRouting);
this.log = options.log;
this.name = 'RestifyRouter';
this.mounts = {};
// Internals
this._anonymusHandlerCounter = 0;
this._findMyWay = new FindMyWay({
defaultRoute: this.defaultRoute.bind(this)
});
}
util.inherits(Router, EventEmitter);
/**
* Returns true if the router generated a 404 for an options request.
*
* TODO: this is relevant for CORS only. Should move this out eventually to a
* userland middleware? This also seems a little like overreach, as there is no
* option to opt out of this behavior today.
*
* @private
* @static
* @function optionsError
* @param {Object} req - the request object
* @param {Object} res - the response object
* @returns {Boolean} is options error
*/
Router.optionsError = function optionsError(req, res) {
var pathname = req.getUrl().pathname;
return req.method === 'OPTIONS' && pathname === '*';
};
/**
* Default route, when no route found
* Responds with a ResourceNotFoundError error.
*
* @private
* @memberof Router
* @instance
* @function defaultRoute
* @param {Request} req - request
* @param {Response} res - response
* @param {Function} next - next
* @returns {undefined} no return value
*/
Router.prototype.defaultRoute = function defaultRoute(req, res, next) {
var self = this;
var pathname = req.getUrl().pathname;
// Allow CORS
if (Router.optionsError(req, res, pathname)) {
res.send(200);
next(null, req, res);
return;
}
// Check for 405 instead of 404
var allowedMethods = http.METHODS.filter(function some(method) {
return self._findMyWay.find(method, pathname);
});
if (allowedMethods.length) {
res.methods = allowedMethods;
res.setHeader('Allow', allowedMethods.join(', '));
var methodErr = new MethodNotAllowedError(
'%s is not allowed',
req.method
);
next(methodErr, req, res);
return;
}
// clean up the url in case of potential xss
// https://github.com/restify/node-restify/issues/1018
var err = new ResourceNotFoundError('%s does not exist', pathname);
next(err, req, res);
};
/**
* Lookup for route
*
* @public
* @memberof Router
* @instance
* @function lookup
* @param {Request} req - request
* @param {Response} res - response
* @param {Function} next - only called when next is called in the last handler
* @returns {undefined} no return value
*/
Router.prototype.lookup = function lookup(req, res, next) {
var self = this;
var url = req.getUrl().pathname;
// Find find-my-way (fmw) route
self._dtraceStart(req);
var fmwRoute = self._findMyWay.find(req.method, url);
self._dtraceEnd(req, res);
// Not found
if (!fmwRoute) {
self.defaultRoute(req, res, function afterRouter(err) {
next(err, req, res);
});
return;
}
// Decorate req
req.params = Object.assign(req.params, fmwRoute.params);
req.route = fmwRoute.store.route;
// Emit routed
self.emit('routed', req, res, req.route);
// Call handler chain
fmwRoute.handler(req, res, next);
};
/**
* Lookup by name
*
* @public
* @memberof Router
* @instance
* @function lookupByName
* @param {String} name - route name
* @param {Request} req - request
* @param {Response} res - response
* @param {Function} next - only called when next is called in the last handler
* @returns {undefined} no return value
*/
Router.prototype.lookupByName = function lookupByName(name, req, res, next) {
var self = this;
var route = self.mounts[name];
if (!route) {
self.defaultRoute(req, res);
return;
}
// Decorate req
req.route = route;
route.chain.handle(req, res, next);
};
/**
* Adds a route.
*
* @public
* @memberof Router
* @instance
* @function mount
* @param {Object} opts - an options object
* @param {String} opts.name - name
* @param {String} opts.method - method
* @param {String} opts.path - path can be any String accepted by
* [find-my-way](https://github.com/delvedor/find-my-way)
* @param {Function[]} handlers - handlers
* @returns {String} returns the route name if creation is successful.
* @fires ...String#mount
*/
Router.prototype.mount = function mount(opts, handlers) {
var self = this;
assert.object(opts, 'opts');
assert.string(opts.method, 'opts.method');
assert.string(opts.name, 'opts.name');
assert.arrayOfFunc(handlers, 'handlers');
var chain = new Chain();
var path = opts.path;
// Route
var route = {
name: opts.name,
method: opts.method,
path: path,
spec: opts,
chain: chain
};
handlers.forEach(function forEach(handler) {
// Assign name to anonymus functions
handler._name =
handler.name || 'handler-' + self._anonymusHandlerCounter++;
// Attach to middleware chain
chain.use(handler);
});
self._findMyWay.on(
route.method,
route.path,
function onRoute(req, res, next) {
chain.handle(req, res, next);
},
{
route: route
}
);
// Store route
self.mounts[route.name] = route;
self.emit('mount', route.method, route.path);
return route;
};
/**
* Unmounts a route.
*
* @public
* @memberof Router
* @instance
* @function unmount
* @param {String} name - the route name
* @returns {String} the name of the deleted route.
*/
Router.prototype.unmount = function unmount(name) {
assert.string(name, 'name');
var route = this.mounts[name];
if (!route) {
return;
}
// TODO: revisit
throw new Error('Unmount is not implemented');
// this._findMyWay.off(route.method, route.path);
// delete this.mounts[name];
// return route;
};
/**
* toString() serialization.
*
* @public
* @memberof Router
* @instance
* @function toString
* @returns {String} stringified router
*/
Router.prototype.toString = function toString() {
return this._findMyWay.prettyPrint();
};
/**
* Return information about the routes registered in the router.
*
* @public
* @memberof Router
* @instance
* @returns {object} The routes in the router.
*/
Router.prototype.getDebugInfo = function getDebugInfo() {
return _.mapValues(this.mounts, function mapValues(route, routeName) {
return {
name: route.name,
method: route.method.toLowerCase(),
path: route.path,
handlers: route.chain.getHandlers()
};
});
};
/**
* Setup request and calls _onRequest to run middlewares and call router
*
* @private
* @memberof Router
* @instance
* @function _dtraceStart
* @param {Request} req - the request object
* @returns {undefined} no return value
* @fires Request,Response#request
*/
Router.prototype._dtraceStart = function _dtraceStart(req) {
if (!req.dtrace) {
return;
}
dtrace._rstfy_probes['route-start'].fire(function fire() {
return [
req.serverName,
req.route.name,
req._dtraceId,
req.method,
req.href(),
req.headers
];
});
};
/**
* Setup request and calls _onRequest to run middlewares and call router
*
* @private
* @memberof Router
* @instance
* @function _dtraceEnd
* @param {Request} req - the request object
* @param {Response} res - the response object
* @returns {undefined} no return value
* @fires Request,Response#request
*/
Router.prototype._dtraceEnd = function _dtraceEnd(req, res) {
if (!req.dtrace) {
return;
}
dtrace._rstfy_probes['route-done'].fire(function fire() {
return [
req.serverName,
req.route.name,
req._dtraceId,
res.statusCode || 200,
res.headers()
];
});
};
module.exports = Router;