You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

576 lines
13 KiB

7 years ago
  1. /**
  2. * Module dependencies.
  3. */
  4. var Route = require('./route');
  5. var Layer = require('./layer');
  6. var methods = require('methods');
  7. var mixin = require('utils-merge');
  8. var debug = require('debug')('express:router');
  9. var parseUrl = require('parseurl');
  10. var utils = require('../utils');
  11. /**
  12. * Module variables.
  13. */
  14. var objectRegExp = /^\[object (\S+)\]$/;
  15. var slice = Array.prototype.slice;
  16. var toString = Object.prototype.toString;
  17. /**
  18. * Initialize a new `Router` with the given `options`.
  19. *
  20. * @param {Object} options
  21. * @return {Router} which is an callable function
  22. * @api public
  23. */
  24. var proto = module.exports = function(options) {
  25. options = options || {};
  26. function router(req, res, next) {
  27. router.handle(req, res, next);
  28. }
  29. // mixin Router class functions
  30. router.__proto__ = proto;
  31. router.params = {};
  32. router._params = [];
  33. router.caseSensitive = options.caseSensitive;
  34. router.mergeParams = options.mergeParams;
  35. router.strict = options.strict;
  36. router.stack = [];
  37. return router;
  38. };
  39. /**
  40. * Map the given param placeholder `name`(s) to the given callback.
  41. *
  42. * Parameter mapping is used to provide pre-conditions to routes
  43. * which use normalized placeholders. For example a _:user_id_ parameter
  44. * could automatically load a user's information from the database without
  45. * any additional code,
  46. *
  47. * The callback uses the same signature as middleware, the only difference
  48. * being that the value of the placeholder is passed, in this case the _id_
  49. * of the user. Once the `next()` function is invoked, just like middleware
  50. * it will continue on to execute the route, or subsequent parameter functions.
  51. *
  52. * Just like in middleware, you must either respond to the request or call next
  53. * to avoid stalling the request.
  54. *
  55. * app.param('user_id', function(req, res, next, id){
  56. * User.find(id, function(err, user){
  57. * if (err) {
  58. * return next(err);
  59. * } else if (!user) {
  60. * return next(new Error('failed to load user'));
  61. * }
  62. * req.user = user;
  63. * next();
  64. * });
  65. * });
  66. *
  67. * @param {String} name
  68. * @param {Function} fn
  69. * @return {app} for chaining
  70. * @api public
  71. */
  72. proto.param = function(name, fn){
  73. // param logic
  74. if ('function' == typeof name) {
  75. this._params.push(name);
  76. return;
  77. }
  78. // apply param functions
  79. var params = this._params;
  80. var len = params.length;
  81. var ret;
  82. if (name[0] === ':') {
  83. name = name.substr(1);
  84. }
  85. for (var i = 0; i < len; ++i) {
  86. if (ret = params[i](name, fn)) {
  87. fn = ret;
  88. }
  89. }
  90. // ensure we end up with a
  91. // middleware function
  92. if ('function' != typeof fn) {
  93. throw new Error('invalid param() call for ' + name + ', got ' + fn);
  94. }
  95. (this.params[name] = this.params[name] || []).push(fn);
  96. return this;
  97. };
  98. /**
  99. * Dispatch a req, res into the router.
  100. *
  101. * @api private
  102. */
  103. proto.handle = function(req, res, done) {
  104. var self = this;
  105. debug('dispatching %s %s', req.method, req.url);
  106. var search = 1 + req.url.indexOf('?');
  107. var pathlength = search ? search - 1 : req.url.length;
  108. var fqdn = req.url[0] !== '/' && 1 + req.url.substr(0, pathlength).indexOf('://');
  109. var protohost = fqdn ? req.url.substr(0, req.url.indexOf('/', 2 + fqdn)) : '';
  110. var idx = 0;
  111. var removed = '';
  112. var slashAdded = false;
  113. var paramcalled = {};
  114. // store options for OPTIONS request
  115. // only used if OPTIONS request
  116. var options = [];
  117. // middleware and routes
  118. var stack = self.stack;
  119. // manage inter-router variables
  120. var parentParams = req.params;
  121. var parentUrl = req.baseUrl || '';
  122. done = restore(done, req, 'baseUrl', 'next', 'params');
  123. // setup next layer
  124. req.next = next;
  125. // for options requests, respond with a default if nothing else responds
  126. if (req.method === 'OPTIONS') {
  127. done = wrap(done, function(old, err) {
  128. if (err || options.length === 0) return old(err);
  129. var body = options.join(',');
  130. return res.set('Allow', body).send(body);
  131. });
  132. }
  133. // setup basic req values
  134. req.baseUrl = parentUrl;
  135. req.originalUrl = req.originalUrl || req.url;
  136. next();
  137. function next(err) {
  138. var layerError = err === 'route'
  139. ? null
  140. : err;
  141. var layer = stack[idx++];
  142. if (slashAdded) {
  143. req.url = req.url.substr(1);
  144. slashAdded = false;
  145. }
  146. if (removed.length !== 0) {
  147. req.baseUrl = parentUrl;
  148. req.url = protohost + removed + req.url.substr(protohost.length);
  149. removed = '';
  150. }
  151. if (!layer) {
  152. setImmediate(done, layerError);
  153. return;
  154. }
  155. self.match_layer(layer, req, res, function (err, path) {
  156. if (err || path === undefined) {
  157. return next(layerError || err);
  158. }
  159. // route object and not middleware
  160. var route = layer.route;
  161. // if final route, then we support options
  162. if (route) {
  163. // we don't run any routes with error first
  164. if (layerError) {
  165. return next(layerError);
  166. }
  167. var method = req.method;
  168. var has_method = route._handles_method(method);
  169. // build up automatic options response
  170. if (!has_method && method === 'OPTIONS') {
  171. options.push.apply(options, route._options());
  172. }
  173. // don't even bother
  174. if (!has_method && method !== 'HEAD') {
  175. return next();
  176. }
  177. // we can now dispatch to the route
  178. req.route = route;
  179. }
  180. // Capture one-time layer values
  181. req.params = self.mergeParams
  182. ? mergeParams(layer.params, parentParams)
  183. : layer.params;
  184. var layerPath = layer.path;
  185. // this should be done for the layer
  186. self.process_params(layer, paramcalled, req, res, function (err) {
  187. if (err) {
  188. return next(layerError || err);
  189. }
  190. if (route) {
  191. return layer.handle_request(req, res, next);
  192. }
  193. trim_prefix(layer, layerError, layerPath, path);
  194. });
  195. });
  196. }
  197. function trim_prefix(layer, layerError, layerPath, path) {
  198. var c = path[layerPath.length];
  199. if (c && '/' !== c && '.' !== c) return next(layerError);
  200. // Trim off the part of the url that matches the route
  201. // middleware (.use stuff) needs to have the path stripped
  202. if (layerPath.length !== 0) {
  203. debug('trim prefix (%s) from url %s', layerPath, req.url);
  204. removed = layerPath;
  205. req.url = protohost + req.url.substr(protohost.length + removed.length);
  206. // Ensure leading slash
  207. if (!fqdn && req.url[0] !== '/') {
  208. req.url = '/' + req.url;
  209. slashAdded = true;
  210. }
  211. // Setup base URL (no trailing slash)
  212. req.baseUrl = parentUrl + (removed[removed.length - 1] === '/'
  213. ? removed.substring(0, removed.length - 1)
  214. : removed);
  215. }
  216. debug('%s %s : %s', layer.name, layerPath, req.originalUrl);
  217. if (layerError) {
  218. layer.handle_error(layerError, req, res, next);
  219. } else {
  220. layer.handle_request(req, res, next);
  221. }
  222. }
  223. };
  224. /**
  225. * Match request to a layer.
  226. *
  227. * @api private
  228. */
  229. proto.match_layer = function match_layer(layer, req, res, done) {
  230. var error = null;
  231. var path;
  232. try {
  233. path = parseUrl(req).pathname;
  234. if (!layer.match(path)) {
  235. path = undefined;
  236. }
  237. } catch (err) {
  238. error = err;
  239. }
  240. done(error, path);
  241. };
  242. /**
  243. * Process any parameters for the layer.
  244. *
  245. * @api private
  246. */
  247. proto.process_params = function(layer, called, req, res, done) {
  248. var params = this.params;
  249. // captured parameters from the layer, keys and values
  250. var keys = layer.keys;
  251. // fast track
  252. if (!keys || keys.length === 0) {
  253. return done();
  254. }
  255. var i = 0;
  256. var name;
  257. var paramIndex = 0;
  258. var key;
  259. var paramVal;
  260. var paramCallbacks;
  261. var paramCalled;
  262. // process params in order
  263. // param callbacks can be async
  264. function param(err) {
  265. if (err) {
  266. return done(err);
  267. }
  268. if (i >= keys.length ) {
  269. return done();
  270. }
  271. paramIndex = 0;
  272. key = keys[i++];
  273. if (!key) {
  274. return done();
  275. }
  276. name = key.name;
  277. paramVal = req.params[name];
  278. paramCallbacks = params[name];
  279. paramCalled = called[name];
  280. if (paramVal === undefined || !paramCallbacks) {
  281. return param();
  282. }
  283. // param previously called with same value or error occurred
  284. if (paramCalled && (paramCalled.error || paramCalled.match === paramVal)) {
  285. // restore value
  286. req.params[name] = paramCalled.value;
  287. // next param
  288. return param(paramCalled.error);
  289. }
  290. called[name] = paramCalled = {
  291. error: null,
  292. match: paramVal,
  293. value: paramVal
  294. };
  295. paramCallback();
  296. }
  297. // single param callbacks
  298. function paramCallback(err) {
  299. var fn = paramCallbacks[paramIndex++];
  300. // store updated value
  301. paramCalled.value = req.params[key.name];
  302. if (err) {
  303. // store error
  304. paramCalled.error = err;
  305. param(err);
  306. return;
  307. }
  308. if (!fn) return param();
  309. try {
  310. fn(req, res, paramCallback, paramVal, key.name);
  311. } catch (e) {
  312. paramCallback(e);
  313. }
  314. }
  315. param();
  316. };
  317. /**
  318. * Use the given middleware function, with optional path, defaulting to "/".
  319. *
  320. * Use (like `.all`) will run for any http METHOD, but it will not add
  321. * handlers for those methods so OPTIONS requests will not consider `.use`
  322. * functions even if they could respond.
  323. *
  324. * The other difference is that _route_ path is stripped and not visible
  325. * to the handler function. The main effect of this feature is that mounted
  326. * handlers can operate without any code changes regardless of the "prefix"
  327. * pathname.
  328. *
  329. * @api public
  330. */
  331. proto.use = function use(fn) {
  332. var offset = 0;
  333. var path = '/';
  334. // default path to '/'
  335. // disambiguate router.use([fn])
  336. if (typeof fn !== 'function') {
  337. var arg = fn;
  338. while (Array.isArray(arg) && arg.length !== 0) {
  339. arg = arg[0];
  340. }
  341. // first arg is the path
  342. if (typeof arg !== 'function') {
  343. offset = 1;
  344. path = fn;
  345. }
  346. }
  347. var callbacks = utils.flatten(slice.call(arguments, offset));
  348. if (callbacks.length === 0) {
  349. throw new TypeError('Router.use() requires middleware functions');
  350. }
  351. callbacks.forEach(function (fn) {
  352. if (typeof fn !== 'function') {
  353. throw new TypeError('Router.use() requires middleware function but got a ' + gettype(fn));
  354. }
  355. // add the middleware
  356. debug('use %s %s', path, fn.name || '<anonymous>');
  357. var layer = new Layer(path, {
  358. sensitive: this.caseSensitive,
  359. strict: false,
  360. end: false
  361. }, fn);
  362. layer.route = undefined;
  363. this.stack.push(layer);
  364. }, this);
  365. return this;
  366. };
  367. /**
  368. * Create a new Route for the given path.
  369. *
  370. * Each route contains a separate middleware stack and VERB handlers.
  371. *
  372. * See the Route api documentation for details on adding handlers
  373. * and middleware to routes.
  374. *
  375. * @param {String} path
  376. * @return {Route}
  377. * @api public
  378. */
  379. proto.route = function(path){
  380. var route = new Route(path);
  381. var layer = new Layer(path, {
  382. sensitive: this.caseSensitive,
  383. strict: this.strict,
  384. end: true
  385. }, route.dispatch.bind(route));
  386. layer.route = route;
  387. this.stack.push(layer);
  388. return route;
  389. };
  390. // create Router#VERB functions
  391. methods.concat('all').forEach(function(method){
  392. proto[method] = function(path){
  393. var route = this.route(path)
  394. route[method].apply(route, slice.call(arguments, 1));
  395. return this;
  396. };
  397. });
  398. // get type for error message
  399. function gettype(obj) {
  400. var type = typeof obj;
  401. if (type !== 'object') {
  402. return type;
  403. }
  404. // inspect [[Class]] for objects
  405. return toString.call(obj)
  406. .replace(objectRegExp, '$1');
  407. }
  408. // merge params with parent params
  409. function mergeParams(params, parent) {
  410. if (typeof parent !== 'object' || !parent) {
  411. return params;
  412. }
  413. // make copy of parent for base
  414. var obj = mixin({}, parent);
  415. // simple non-numeric merging
  416. if (!(0 in params) || !(0 in parent)) {
  417. return mixin(obj, params);
  418. }
  419. var i = 0;
  420. var o = 0;
  421. // determine numeric gaps
  422. while (i === o || o in parent) {
  423. if (i in params) i++;
  424. if (o in parent) o++;
  425. }
  426. // offset numeric indices in params before merge
  427. for (i--; i >= 0; i--) {
  428. params[i + o] = params[i];
  429. // create holes for the merge when necessary
  430. if (i < o) {
  431. delete params[i];
  432. }
  433. }
  434. return mixin(parent, params);
  435. }
  436. // restore obj props after function
  437. function restore(fn, obj) {
  438. var props = new Array(arguments.length - 2);
  439. var vals = new Array(arguments.length - 2);
  440. for (var i = 0; i < props.length; i++) {
  441. props[i] = arguments[i + 2];
  442. vals[i] = obj[props[i]];
  443. }
  444. return function(err){
  445. // restore vals
  446. for (var i = 0; i < props.length; i++) {
  447. obj[props[i]] = vals[i];
  448. }
  449. return fn.apply(this, arguments);
  450. };
  451. }
  452. // wrap a function
  453. function wrap(old, fn) {
  454. return function proxy() {
  455. var args = new Array(arguments.length + 1);
  456. args[0] = old;
  457. for (var i = 0, len = arguments.length; i < len; i++) {
  458. args[i + 1] = arguments[i];
  459. }
  460. fn.apply(this, args);
  461. };
  462. }