Skip to content
Myr

index.js

This file

Path

lib/router/index.js

640 lines · 14.1 KiB · JavaScript

Last changed by

perf: enable strict modeDouglas Christopher Wilsonbefore adoptione71014f

History of this file

Take it

The walk stopped after 200 commits: lines older than 6bc7574 point at it.

docs: add license commentsDouglas Christopher Wilsonbefore adoption95ad276

lines 1–7why, one step back
1/*!
2 * express3 * Copyright(c) 2009-2013 TJ Holowaychuk4 * Copyright(c) 2013 Roman Shtylman5 * Copyright(c) 2014-2015 Douglas Christopher Wilson6 * MIT Licensed7 */

Improve error message for bad app.use argumentsDouglas Christopher Wilsonbefore adoptionbf1980f

line 8why, one step back
8

perf: enable strict modeDouglas Christopher Wilsonbefore adoptione71014f

lines 9–10why, one step back
9'use strict';
10

docs: typo fixesDouglas Christopher Wilsonbefore adoption6bc7574

lines 11–19why, one step back
11/**
12 * Module dependencies.13 */1415var Route = require('./route');16var Layer = require('./layer');17var methods = require('methods');18var mixin = require('utils-merge');19var debug = require('debug')('express:router');

Deprecate leading colon in name for app.paramDouglas Christopher Wilsonbefore adoptionfc4eb6d

line 20why, one step back
20var deprecate = require('depd')('express');

Use array-flatten module for flattening arraysDeepak Kapoorbefore adoptionf7e94a3

line 21why, one step back
21var flatten = require('array-flatten');

docs: typo fixesDouglas Christopher Wilsonbefore adoption6bc7574

line 22why, one step back
22var parseUrl = require('parseurl');

Improve error message for bad app.use argumentsDouglas Christopher Wilsonbefore adoptionbf1980f

lines 23–28why, one step back
23
24/**25 * Module variables.26 */2728var objectRegExp = /^\[object (\S+)\]$/;

docs: typo fixesDouglas Christopher Wilsonbefore adoption6bc7574

lines 29–93why, one step back
29var slice = Array.prototype.slice;
30var toString = Object.prototype.toString;3132/**33 * Initialize a new `Router` with the given `options`.34 *35 * @param {Object} options36 * @return {Router} which is an callable function37 * @api public38 */3940var proto = module.exports = function(options) {41 options = options || {};4243 function router(req, res, next) {44 router.handle(req, res, next);45 }4647 // mixin Router class functions48 router.__proto__ = proto;4950 router.params = {};51 router._params = [];52 router.caseSensitive = options.caseSensitive;53 router.mergeParams = options.mergeParams;54 router.strict = options.strict;55 router.stack = [];5657 return router;58};5960/**61 * Map the given param placeholder `name`(s) to the given callback.62 *63 * Parameter mapping is used to provide pre-conditions to routes64 * which use normalized placeholders. For example a _:user_id_ parameter65 * could automatically load a user's information from the database without66 * any additional code,67 *68 * The callback uses the same signature as middleware, the only difference69 * being that the value of the placeholder is passed, in this case the _id_70 * of the user. Once the `next()` function is invoked, just like middleware71 * it will continue on to execute the route, or subsequent parameter functions.72 *73 * Just like in middleware, you must either respond to the request or call next74 * to avoid stalling the request.75 *76 * app.param('user_id', function(req, res, next, id){77 * User.find(id, function(err, user){78 * if (err) {79 * return next(err);80 * } else if (!user) {81 * return next(new Error('failed to load user'));82 * }83 * req.user = user;84 * next();85 * });86 * });87 *88 * @param {String} name89 * @param {Function} fn90 * @return {app} for chaining91 * @api public92 */93

Deprecate app.param(fn)Douglas Christopher Wilsonbefore adoption591e89e

line 94why, one step back
94proto.param = function param(name, fn) {

docs: typo fixesDouglas Christopher Wilsonbefore adoption6bc7574

line 95why, one step back
95 // param logic

Deprecate app.param(fn)Douglas Christopher Wilsonbefore adoption591e89e

lines 96–97why, one step back
96 if (typeof name === 'function') {
97 deprecate('router.param(fn): Refactor to use path params');

docs: typo fixesDouglas Christopher Wilsonbefore adoption6bc7574

lines 98–107why, one step back
98 this._params.push(name);
99 return;100 }101102 // apply param functions103 var params = this._params;104 var len = params.length;105 var ret;106107 if (name[0] === ':') {

Improve deprecation message for router.param()Douglas Christopher Wilsonbefore adoption1616079

line 108why, one step back
108 deprecate('router.param(' + JSON.stringify(name) + ', fn): Use router.param(' + JSON.stringify(name.substr(1)) + ', fn) instead');

docs: typo fixesDouglas Christopher Wilsonbefore adoption6bc7574

lines 109–140why, one step back
109 name = name.substr(1);
110 }111112 for (var i = 0; i < len; ++i) {113 if (ret = params[i](name, fn)) {114 fn = ret;115 }116 }117118 // ensure we end up with a119 // middleware function120 if ('function' != typeof fn) {121 throw new Error('invalid param() call for ' + name + ', got ' + fn);122 }123124 (this.params[name] = this.params[name] || []).push(fn);125 return this;126};127128/**129 * Dispatch a req, res into the router.130 *131 * @api private132 */133134proto.handle = function(req, res, done) {135 var self = this;136137 debug('dispatching %s %s', req.method, req.url);138139 var search = 1 + req.url.indexOf('?');140 var pathlength = search ? search - 1 : req.url.length;

Fix handling of URLs containing :// in the pathAria Stewartbefore adoptioneabd456

line 141why, one step back
141 var fqdn = req.url[0] !== '/' && 1 + req.url.substr(0, pathlength).indexOf('://');

docs: typo fixesDouglas Christopher Wilsonbefore adoption6bc7574

lines 142–166why, one step back
142 var protohost = fqdn ? req.url.substr(0, req.url.indexOf('/', 2 + fqdn)) : '';
143 var idx = 0;144 var removed = '';145 var slashAdded = false;146 var paramcalled = {};147148 // store options for OPTIONS request149 // only used if OPTIONS request150 var options = [];151152 // middleware and routes153 var stack = self.stack;154155 // manage inter-router variables156 var parentParams = req.params;157 var parentUrl = req.baseUrl || '';158 done = restore(done, req, 'baseUrl', 'next', 'params');159160 // setup next layer161 req.next = next;162163 // for options requests, respond with a default if nothing else responds164 if (req.method === 'OPTIONS') {165 done = wrap(done, function(old, err) {166 if (err || options.length === 0) return old(err);

Fix crash from error within OPTIONS response handlerDouglas Christopher Wilsonbefore adoptiondab9222

line 167why, one step back
167 sendOptionsResponse(res, options, old);

docs: typo fixesDouglas Christopher Wilsonbefore adoption6bc7574

lines 168–181why, one step back
168 });
169 }170171 // setup basic req values172 req.baseUrl = parentUrl;173 req.originalUrl = req.originalUrl || req.url;174175 next();176177 function next(err) {178 var layerError = err === 'route'179 ? null180 : err;181

Match routes iteratively to prevent stack overflowsDouglas Christopher Wilsonbefore adoptionec8daf0

line 182why, one step back
182 // remove added slash

docs: typo fixesDouglas Christopher Wilsonbefore adoption6bc7574

lines 183–187why, one step back
183 if (slashAdded) {
184 req.url = req.url.substr(1);185 slashAdded = false;186 }187

Match routes iteratively to prevent stack overflowsDouglas Christopher Wilsonbefore adoptionec8daf0

line 188why, one step back
188 // restore altered req.url

docs: typo fixesDouglas Christopher Wilsonbefore adoption6bc7574

lines 189–194why, one step back
189 if (removed.length !== 0) {
190 req.baseUrl = parentUrl;191 req.url = protohost + removed + req.url.substr(protohost.length);192 removed = '';193 }194

Match routes iteratively to prevent stack overflowsDouglas Christopher Wilsonbefore adoptionec8daf0

lines 195–196why, one step back
195 // no more matching layers
196 if (idx >= stack.length) {

Correctly invoke async router callback asynchronouslyDouglas Christopher Wilsonbefore adoption5fab60b

lines 197–198why, one step back
197 setImmediate(done, layerError);
198 return;

docs: typo fixesDouglas Christopher Wilsonbefore adoption6bc7574

lines 199–200why, one step back
199 }
200

Match routes iteratively to prevent stack overflowsDouglas Christopher Wilsonbefore adoptionec8daf0

lines 201–220why, one step back
201 // get pathname of request
202 var path = getPathname(req);203204 if (path == null) {205 return done(layerError);206 }207208 // find next matching layer209 var layer;210 var match;211 var route;212213 while (match !== true && idx < stack.length) {214 layer = stack[idx++];215 match = matchLayer(layer, path);216 route = layer.route;217218 if (typeof match !== 'boolean') {219 // hold on to layerError220 layerError = layerError || match;

docs: typo fixesDouglas Christopher Wilsonbefore adoption6bc7574

lines 221–222why, one step back
221 }
222

Match routes iteratively to prevent stack overflowsDouglas Christopher Wilsonbefore adoptionec8daf0

lines 223–225why, one step back
223 if (match !== true) {
224 continue;225 }

docs: typo fixesDouglas Christopher Wilsonbefore adoption6bc7574

line 226why, one step back
226

Match routes iteratively to prevent stack overflowsDouglas Christopher Wilsonbefore adoptionec8daf0

lines 227–230why, one step back
227 if (!route) {
228 // process non-route handlers normally229 continue;230 }

docs: typo fixesDouglas Christopher Wilsonbefore adoption6bc7574

line 231why, one step back
231

Match routes iteratively to prevent stack overflowsDouglas Christopher Wilsonbefore adoptionec8daf0

lines 232–236why, one step back
232 if (layerError) {
233 // routes do not match with a pending error234 match = false;235 continue;236 }

docs: typo fixesDouglas Christopher Wilsonbefore adoption6bc7574

line 237why, one step back
237

Match routes iteratively to prevent stack overflowsDouglas Christopher Wilsonbefore adoptionec8daf0

lines 238–239why, one step back
238 var method = req.method;
239 var has_method = route._handles_method(method);

docs: typo fixesDouglas Christopher Wilsonbefore adoption6bc7574

line 240why, one step back
240

Match routes iteratively to prevent stack overflowsDouglas Christopher Wilsonbefore adoptionec8daf0

lines 241–244why, one step back
241 // build up automatic options response
242 if (!has_method && method === 'OPTIONS') {243 appendMethods(options, route._options());244 }

docs: typo fixesDouglas Christopher Wilsonbefore adoption6bc7574

line 245why, one step back
245

Match routes iteratively to prevent stack overflowsDouglas Christopher Wilsonbefore adoptionec8daf0

lines 246–249why, one step back
246 // don't even bother matching route
247 if (!has_method && method !== 'HEAD') {248 match = false;249 continue;

docs: typo fixesDouglas Christopher Wilsonbefore adoption6bc7574

line 250why, one step back
250 }

Match routes iteratively to prevent stack overflowsDouglas Christopher Wilsonbefore adoptionec8daf0

line 251why, one step back
251 }

docs: typo fixesDouglas Christopher Wilsonbefore adoption6bc7574

line 252why, one step back
252

Match routes iteratively to prevent stack overflowsDouglas Christopher Wilsonbefore adoptionec8daf0

lines 253–256why, one step back
253 // no match
254 if (match !== true) {255 return done(layerError);256 }

docs: typo fixesDouglas Christopher Wilsonbefore adoption6bc7574

line 257why, one step back
257

Match routes iteratively to prevent stack overflowsDouglas Christopher Wilsonbefore adoptionec8daf0

lines 258–261why, one step back
258 // store route for dispatch on change
259 if (route) {260 req.route = route;261 }

docs: typo fixesDouglas Christopher Wilsonbefore adoption6bc7574

line 262why, one step back
262

Match routes iteratively to prevent stack overflowsDouglas Christopher Wilsonbefore adoptionec8daf0

lines 263–267why, one step back
263 // Capture one-time layer values
264 req.params = self.mergeParams265 ? mergeParams(layer.params, parentParams)266 : layer.params;267 var layerPath = layer.path;

docs: typo fixesDouglas Christopher Wilsonbefore adoption6bc7574

line 268why, one step back
268

Match routes iteratively to prevent stack overflowsDouglas Christopher Wilsonbefore adoptionec8daf0

lines 269–279why, one step back
269 // this should be done for the layer
270 self.process_params(layer, paramcalled, req, res, function (err) {271 if (err) {272 return next(layerError || err);273 }274275 if (route) {276 return layer.handle_request(req, res, next);277 }278279 trim_prefix(layer, layerError, layerPath, path);

docs: typo fixesDouglas Christopher Wilsonbefore adoption6bc7574

lines 280–368why, one step back
280 });
281 }282283 function trim_prefix(layer, layerError, layerPath, path) {284 var c = path[layerPath.length];285 if (c && '/' !== c && '.' !== c) return next(layerError);286287 // Trim off the part of the url that matches the route288 // middleware (.use stuff) needs to have the path stripped289 if (layerPath.length !== 0) {290 debug('trim prefix (%s) from url %s', layerPath, req.url);291 removed = layerPath;292 req.url = protohost + req.url.substr(protohost.length + removed.length);293294 // Ensure leading slash295 if (!fqdn && req.url[0] !== '/') {296 req.url = '/' + req.url;297 slashAdded = true;298 }299300 // Setup base URL (no trailing slash)301 req.baseUrl = parentUrl + (removed[removed.length - 1] === '/'302 ? removed.substring(0, removed.length - 1)303 : removed);304 }305306 debug('%s %s : %s', layer.name, layerPath, req.originalUrl);307308 if (layerError) {309 layer.handle_error(layerError, req, res, next);310 } else {311 layer.handle_request(req, res, next);312 }313 }314};315316/**317 * Process any parameters for the layer.318 *319 * @api private320 */321322proto.process_params = function(layer, called, req, res, done) {323 var params = this.params;324325 // captured parameters from the layer, keys and values326 var keys = layer.keys;327328 // fast track329 if (!keys || keys.length === 0) {330 return done();331 }332333 var i = 0;334 var name;335 var paramIndex = 0;336 var key;337 var paramVal;338 var paramCallbacks;339 var paramCalled;340341 // process params in order342 // param callbacks can be async343 function param(err) {344 if (err) {345 return done(err);346 }347348 if (i >= keys.length ) {349 return done();350 }351352 paramIndex = 0;353 key = keys[i++];354355 if (!key) {356 return done();357 }358359 name = key.name;360 paramVal = req.params[name];361 paramCallbacks = params[name];362 paramCalled = called[name];363364 if (paramVal === undefined || !paramCallbacks) {365 return param();366 }367368 // param previously called with same value or error occurred

Fix issue where next('route') in app.param would incorrectly skip valuesRadu Danbefore adoption8da51e3

lines 369–370why, one step back
369 if (paramCalled && (paramCalled.match === paramVal
370 || (paramCalled.error && paramCalled.error !== 'route'))) {

docs: typo fixesDouglas Christopher Wilsonbefore adoption6bc7574

lines 371–432why, one step back
371 // restore value
372 req.params[name] = paramCalled.value;373374 // next param375 return param(paramCalled.error);376 }377378 called[name] = paramCalled = {379 error: null,380 match: paramVal,381 value: paramVal382 };383384 paramCallback();385 }386387 // single param callbacks388 function paramCallback(err) {389 var fn = paramCallbacks[paramIndex++];390391 // store updated value392 paramCalled.value = req.params[key.name];393394 if (err) {395 // store error396 paramCalled.error = err;397 param(err);398 return;399 }400401 if (!fn) return param();402403 try {404 fn(req, res, paramCallback, paramVal, key.name);405 } catch (e) {406 paramCallback(e);407 }408 }409410 param();411};412413/**414 * Use the given middleware function, with optional path, defaulting to "/".415 *416 * Use (like `.all`) will run for any http METHOD, but it will not add417 * handlers for those methods so OPTIONS requests will not consider `.use`418 * functions even if they could respond.419 *420 * The other difference is that _route_ path is stripped and not visible421 * to the handler function. The main effect of this feature is that mounted422 * handlers can operate without any code changes regardless of the "prefix"423 * pathname.424 *425 * @api public426 */427428proto.use = function use(fn) {429 var offset = 0;430 var path = '/';431432 // default path to '/'

Fix router.use to accept array of middleware without pathDouglas Christopher Wilsonbefore adoption7289171

line 433why, one step back
433 // disambiguate router.use([fn])

docs: typo fixesDouglas Christopher Wilsonbefore adoption6bc7574

line 434why, one step back
434 if (typeof fn !== 'function') {

Fix router.use to accept array of middleware without pathDouglas Christopher Wilsonbefore adoption7289171

lines 435–445why, one step back
435 var arg = fn;
436437 while (Array.isArray(arg) && arg.length !== 0) {438 arg = arg[0];439 }440441 // first arg is the path442 if (typeof arg !== 'function') {443 offset = 1;444 path = fn;445 }

docs: typo fixesDouglas Christopher Wilsonbefore adoption6bc7574

lines 446–447why, one step back
446 }
447

Use array-flatten module for flattening arraysDeepak Kapoorbefore adoptionf7e94a3

line 448why, one step back
448 var callbacks = flatten(slice.call(arguments, offset));

docs: typo fixesDouglas Christopher Wilsonbefore adoption6bc7574

lines 449–450why, one step back
449
450 if (callbacks.length === 0) {

Improve error message for bad app.use argumentsDouglas Christopher Wilsonbefore adoptionbf1980f

line 451why, one step back
451 throw new TypeError('Router.use() requires middleware functions');

docs: typo fixesDouglas Christopher Wilsonbefore adoption6bc7574

lines 452–455why, one step back
452 }
453454 callbacks.forEach(function (fn) {455 if (typeof fn !== 'function') {

Improve error message for bad app.use argumentsDouglas Christopher Wilsonbefore adoptionbf1980f

line 456why, one step back
456 throw new TypeError('Router.use() requires middleware function but got a ' + gettype(fn));

docs: typo fixesDouglas Christopher Wilsonbefore adoption6bc7574

lines 457–462why, one step back
457 }
458459 // add the middleware460 debug('use %s %s', path, fn.name || '<anonymous>');461462 var layer = new Layer(path, {

Pass context to .forEach instead of closurelemmybefore adoptiondfa7ee4

line 463why, one step back
463 sensitive: this.caseSensitive,

docs: typo fixesDouglas Christopher Wilsonbefore adoption6bc7574

lines 464–469why, one step back
464 strict: false,
465 end: false466 }, fn);467468 layer.route = undefined;469

Pass context to .forEach instead of closurelemmybefore adoptiondfa7ee4

lines 470–471why, one step back
470 this.stack.push(layer);
471 }, this);

docs: typo fixesDouglas Christopher Wilsonbefore adoption6bc7574

lines 472–511why, one step back
472
473 return this;474};475476/**477 * Create a new Route for the given path.478 *479 * Each route contains a separate middleware stack and VERB handlers.480 *481 * See the Route api documentation for details on adding handlers482 * and middleware to routes.483 *484 * @param {String} path485 * @return {Route}486 * @api public487 */488489proto.route = function(path){490 var route = new Route(path);491492 var layer = new Layer(path, {493 sensitive: this.caseSensitive,494 strict: this.strict,495 end: true496 }, route.dispatch.bind(route));497498 layer.route = route;499500 this.stack.push(layer);501 return route;502};503504// create Router#VERB functions505methods.concat('all').forEach(function(method){506 proto[method] = function(path){507 var route = this.route(path)508 route[method].apply(route, slice.call(arguments, 1));509 return this;510 };511});

Fix Allow header for OPTIONS to not contain duplicate methodsDouglas Christopher Wilsonbefore adoption12626ae

lines 512–521why, one step back
512
513// append methods to a list of methods514function appendMethods(list, addition) {515 for (var i = 0; i < addition.length; i++) {516 var method = addition[i];517 if (list.indexOf(method) === -1) {518 list.push(method);519 }520 }521}

Improve error message for bad app.use argumentsDouglas Christopher Wilsonbefore adoptionbf1980f

line 522why, one step back
522

Match routes iteratively to prevent stack overflowsDouglas Christopher Wilsonbefore adoptionec8daf0

lines 523–531why, one step back
523// get pathname of request
524function getPathname(req) {525 try {526 return parseUrl(req).pathname;527 } catch (err) {528 return undefined;529 }530}531

Improve error message for bad app.use argumentsDouglas Christopher Wilsonbefore adoptionbf1980f

lines 532–542why, one step back
532// get type for error message
533function gettype(obj) {534 var type = typeof obj;535536 if (type !== 'object') {537 return type;538 }539540 // inspect [[Class]] for objects541 return toString.call(obj)542 .replace(objectRegExp, '$1');

Match routes iteratively to prevent stack overflowsDouglas Christopher Wilsonbefore adoptionec8daf0

lines 543–558why, one step back
543}
544545/**546 * Match path to a layer.547 *548 * @param {Layer} layer549 * @param {string} path550 * @private551 */552553function matchLayer(layer, path) {554 try {555 return layer.match(path);556 } catch (err) {557 return err;558 }

Improve error message for bad app.use argumentsDouglas Christopher Wilsonbefore adoptionbf1980f

line 559why, one step back
559}

docs: typo fixesDouglas Christopher Wilsonbefore adoption6bc7574

lines 560–614why, one step back
560
561// merge params with parent params562function mergeParams(params, parent) {563 if (typeof parent !== 'object' || !parent) {564 return params;565 }566567 // make copy of parent for base568 var obj = mixin({}, parent);569570 // simple non-numeric merging571 if (!(0 in params) || !(0 in parent)) {572 return mixin(obj, params);573 }574575 var i = 0;576 var o = 0;577578 // determine numeric gaps579 while (i === o || o in parent) {580 if (i in params) i++;581 if (o in parent) o++;582 }583584 // offset numeric indices in params before merge585 for (i--; i >= 0; i--) {586 params[i + o] = params[i];587588 // create holes for the merge when necessary589 if (i < o) {590 delete params[i];591 }592 }593594 return mixin(parent, params);595}596597// restore obj props after function598function restore(fn, obj) {599 var props = new Array(arguments.length - 2);600 var vals = new Array(arguments.length - 2);601602 for (var i = 0; i < props.length; i++) {603 props[i] = arguments[i + 2];604 vals[i] = obj[props[i]];605 }606607 return function(err){608 // restore vals609 for (var i = 0; i < props.length; i++) {610 obj[props[i]] = vals[i];611 }612613 return fn.apply(this, arguments);614 };

Fix crash from error within OPTIONS response handlerDouglas Christopher Wilsonbefore adoptiondab9222

lines 615–625why, one step back
615}
616617// send an OPTIONS response618function sendOptionsResponse(res, options, next) {619 try {620 var body = options.join(',');621 res.set('Allow', body);622 res.send(body);623 } catch (err) {624 next(err);625 }

docs: typo fixesDouglas Christopher Wilsonbefore adoption6bc7574

lines 626–640why, one step back
626}
627628// wrap a function629function wrap(old, fn) {630 return function proxy() {631 var args = new Array(arguments.length + 1);632633 args[0] = old;634 for (var i = 0, len = arguments.length; i < len; i++) {635 args[i + 1] = arguments[i];636 }637638 fn.apply(this, args);639 };640}