index.js 15 KB

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