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

1/*!2 * express3 * Copyright(c) 2009-2013 TJ Holowaychuk4 * Copyright(c) 2013 Roman Shtylman5 * Copyright(c) 2014-2015 Douglas Christopher Wilson6 * MIT Licensed7 */89'use strict';1011/**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');20var deprecate = require('depd')('express');21var flatten = require('array-flatten');22var parseUrl = require('parseurl');2324/**25 * Module variables.26 */2728var objectRegExp = /^\[object (\S+)\]$/;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 */9394proto.param = function param(name, fn) {95  // param logic96  if (typeof name === 'function') {97    deprecate('router.param(fn): Refactor to use path params');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] === ':') {108    deprecate('router.param(' + JSON.stringify(name) + ', fn): Use router.param(' + JSON.stringify(name.substr(1)) + ', fn) instead');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;141  var fqdn = req.url[0] !== '/' && 1 + req.url.substr(0, pathlength).indexOf('://');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);167      sendOptionsResponse(res, options, old);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;181182    // remove added slash183    if (slashAdded) {184      req.url = req.url.substr(1);185      slashAdded = false;186    }187188    // restore altered req.url189    if (removed.length !== 0) {190      req.baseUrl = parentUrl;191      req.url = protohost + removed + req.url.substr(protohost.length);192      removed = '';193    }194195    // no more matching layers196    if (idx >= stack.length) {197      setImmediate(done, layerError);198      return;199    }200201    // get pathname of request202    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;221      }222223      if (match !== true) {224        continue;225      }226227      if (!route) {228        // process non-route handlers normally229        continue;230      }231232      if (layerError) {233        // routes do not match with a pending error234        match = false;235        continue;236      }237238      var method = req.method;239      var has_method = route._handles_method(method);240241      // build up automatic options response242      if (!has_method && method === 'OPTIONS') {243        appendMethods(options, route._options());244      }245246      // don't even bother matching route247      if (!has_method && method !== 'HEAD') {248        match = false;249        continue;250      }251    }252253    // no match254    if (match !== true) {255      return done(layerError);256    }257258    // store route for dispatch on change259    if (route) {260      req.route = route;261    }262263    // Capture one-time layer values264    req.params = self.mergeParams265      ? mergeParams(layer.params, parentParams)266      : layer.params;267    var layerPath = layer.path;268269    // this should be done for the layer270    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);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 occurred369    if (paramCalled && (paramCalled.match === paramVal370      || (paramCalled.error && paramCalled.error !== 'route'))) {371      // restore value372      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 '/'433  // disambiguate router.use([fn])434  if (typeof fn !== 'function') {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    }446  }447448  var callbacks = flatten(slice.call(arguments, offset));449450  if (callbacks.length === 0) {451    throw new TypeError('Router.use() requires middleware functions');452  }453454  callbacks.forEach(function (fn) {455    if (typeof fn !== 'function') {456      throw new TypeError('Router.use() requires middleware function but got a ' + gettype(fn));457    }458459    // add the middleware460    debug('use %s %s', path, fn.name || '<anonymous>');461462    var layer = new Layer(path, {463      sensitive: this.caseSensitive,464      strict: false,465      end: false466    }, fn);467468    layer.route = undefined;469470    this.stack.push(layer);471  }, this);472473  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});512513// 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}522523// get pathname of request524function getPathname(req) {525  try {526    return parseUrl(req).pathname;527  } catch (err) {528    return undefined;529  }530}531532// get type for error message533function 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');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  }559}560561// 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  };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  }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}