Skip to content
Myr

application.js

This file

Path

lib/application.js

607 lines · 13.4 KiB · JavaScript

Last changed by

Merge tag '3.20.0'Douglas Christopher Wilsonbefore adoption531f024

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/**10 * Module dependencies.11 * @api private12 */1314var finalhandler = require('finalhandler');15var flatten = require('./utils').flatten;16var Router = require('./router');17var methods = require('methods');18var middleware = require('./middleware/init');19var query = require('./middleware/query');20var debug = require('debug')('express:application');21var View = require('./view');22var http = require('http');23var compileETag = require('./utils').compileETag;24var compileQueryParser = require('./utils').compileQueryParser;25var compileTrust = require('./utils').compileTrust;26var deprecate = require('depd')('express');27var merge = require('utils-merge');28var resolve = require('path').resolve;29var slice = Array.prototype.slice;3031/**32 * Application prototype.33 */3435var app = exports = module.exports = {};3637/**38 * Variable for trust proxy inheritance back-compat39 * @api private40 */4142var trustProxyDefaultSymbol = '@@symbol:trust_proxy_default';4344/**45 * Initialize the server.46 *47 *   - setup default configuration48 *   - setup default middleware49 *   - setup route reflection methods50 *51 * @api private52 */5354app.init = function(){55  this.cache = {};56  this.settings = {};57  this.engines = {};58  this.defaultConfiguration();59};6061/**62 * Initialize application configuration.63 *64 * @api private65 */6667app.defaultConfiguration = function(){68  // default settings69  this.enable('x-powered-by');70  this.set('etag', 'weak');71  var env = process.env.NODE_ENV || 'development';72  this.set('env', env);73  this.set('query parser', 'extended');74  this.set('subdomain offset', 2);75  this.set('trust proxy', false);7677  // trust proxy inherit back-compat78  Object.defineProperty(this.settings, trustProxyDefaultSymbol, {79    configurable: true,80    value: true81  });8283  debug('booting in %s mode', env);8485  this.on('mount', function onmount(parent) {86    // inherit trust proxy87    if (this.settings[trustProxyDefaultSymbol] === true88      && typeof parent.settings['trust proxy fn'] === 'function') {89      delete this.settings['trust proxy'];90      delete this.settings['trust proxy fn'];91    }9293    // inherit protos94    this.request.__proto__ = parent.request;95    this.response.__proto__ = parent.response;96    this.engines.__proto__ = parent.engines;97    this.settings.__proto__ = parent.settings;98  });99100  // setup locals101  this.locals = Object.create(null);102103  // top-most app is mounted at /104  this.mountpath = '/';105106  // default locals107  this.locals.settings = this.settings;108109  // default configuration110  this.set('view', View);111  this.set('views', resolve('views'));112  this.set('jsonp callback name', 'callback');113114  if (env === 'production') {115    this.enable('view cache');116  }117118  Object.defineProperty(this, 'router', {119    get: function() {120      throw new Error('\'app.router\' is deprecated!\nPlease see the 3.x to 4.x migration guide for details on how to update your app.');121    }122  });123};124125/**126 * lazily adds the base router if it has not yet been added.127 *128 * We cannot add the base router in the defaultConfiguration because129 * it reads app settings which might be set after that has run.130 *131 * @api private132 */133app.lazyrouter = function() {134  if (!this._router) {135    this._router = new Router({136      caseSensitive: this.enabled('case sensitive routing'),137      strict: this.enabled('strict routing')138    });139140    this._router.use(query(this.get('query parser fn')));141    this._router.use(middleware.init(this));142  }143};144145/**146 * Dispatch a req, res pair into the application. Starts pipeline processing.147 *148 * If no _done_ callback is provided, then default error handlers will respond149 * in the event of an error bubbling through the stack.150 *151 * @api private152 */153154app.handle = function(req, res, done) {155  var router = this._router;156157  // final handler158  done = done || finalhandler(req, res, {159    env: this.get('env'),160    onerror: logerror.bind(this)161  });162163  // no routes164  if (!router) {165    debug('no routes defined on app');166    done();167    return;168  }169170  router.handle(req, res, done);171};172173/**174 * Proxy `Router#use()` to add middleware to the app router.175 * See Router#use() documentation for details.176 *177 * If the _fn_ parameter is an express app, then it will be178 * mounted at the _route_ specified.179 *180 * @api public181 */182183app.use = function use(fn) {184  var offset = 0;185  var path = '/';186187  // default path to '/'188  // disambiguate app.use([fn])189  if (typeof fn !== 'function') {190    var arg = fn;191192    while (Array.isArray(arg) && arg.length !== 0) {193      arg = arg[0];194    }195196    // first arg is the path197    if (typeof arg !== 'function') {198      offset = 1;199      path = fn;200    }201  }202203  var fns = flatten(slice.call(arguments, offset));204205  if (fns.length === 0) {206    throw new TypeError('app.use() requires middleware functions');207  }208209  // setup router210  this.lazyrouter();211  var router = this._router;212213  fns.forEach(function (fn) {214    // non-express app215    if (!fn || !fn.handle || !fn.set) {216      return router.use(path, fn);217    }218219    debug('.use app under %s', path);220    fn.mountpath = path;221    fn.parent = this;222223    // restore .app property on req and res224    router.use(path, function mounted_app(req, res, next) {225      var orig = req.app;226      fn.handle(req, res, function (err) {227        req.__proto__ = orig.request;228        res.__proto__ = orig.response;229        next(err);230      });231    });232233    // mounted an app234    fn.emit('mount', this);235  }, this);236237  return this;238};239240/**241 * Proxy to the app `Router#route()`242 * Returns a new `Route` instance for the _path_.243 *244 * Routes are isolated middleware stacks for specific paths.245 * See the Route api docs for details.246 *247 * @api public248 */249250app.route = function(path){251  this.lazyrouter();252  return this._router.route(path);253};254255/**256 * Register the given template engine callback `fn`257 * as `ext`.258 *259 * By default will `require()` the engine based on the260 * file extension. For example if you try to render261 * a "foo.jade" file Express will invoke the following internally:262 *263 *     app.engine('jade', require('jade').__express);264 *265 * For engines that do not provide `.__express` out of the box,266 * or if you wish to "map" a different extension to the template engine267 * you may use this method. For example mapping the EJS template engine to268 * ".html" files:269 *270 *     app.engine('html', require('ejs').renderFile);271 *272 * In this case EJS provides a `.renderFile()` method with273 * the same signature that Express expects: `(path, options, callback)`,274 * though note that it aliases this method as `ejs.__express` internally275 * so if you're using ".ejs" extensions you dont need to do anything.276 *277 * Some template engines do not follow this convention, the278 * [Consolidate.js](https://github.com/tj/consolidate.js)279 * library was created to map all of node's popular template280 * engines to follow this convention, thus allowing them to281 * work seamlessly within Express.282 *283 * @param {String} ext284 * @param {Function} fn285 * @return {app} for chaining286 * @api public287 */288289app.engine = function(ext, fn){290  if ('function' != typeof fn) throw new Error('callback function required');291  if ('.' != ext[0]) ext = '.' + ext;292  this.engines[ext] = fn;293  return this;294};295296/**297 * Proxy to `Router#param()` with one added api feature. The _name_ parameter298 * can be an array of names.299 *300 * See the Router#param() docs for more details.301 *302 * @param {String|Array} name303 * @param {Function} fn304 * @return {app} for chaining305 * @api public306 */307308app.param = function(name, fn){309  this.lazyrouter();310311  if (Array.isArray(name)) {312    name.forEach(function(key) {313      this.param(key, fn);314    }, this);315    return this;316  }317318  this._router.param(name, fn);319  return this;320};321322/**323 * Assign `setting` to `val`, or return `setting`'s value.324 *325 *    app.set('foo', 'bar');326 *    app.get('foo');327 *    // => "bar"328 *329 * Mounted servers inherit their parent server's settings.330 *331 * @param {String} setting332 * @param {*} [val]333 * @return {Server} for chaining334 * @api public335 */336337app.set = function(setting, val){338  if (arguments.length === 1) {339    // app.get(setting)340    return this.settings[setting];341  }342343  // set value344  this.settings[setting] = val;345346  // trigger matched settings347  switch (setting) {348    case 'etag':349      debug('compile etag %s', val);350      this.set('etag fn', compileETag(val));351      break;352    case 'query parser':353      debug('compile query parser %s', val);354      this.set('query parser fn', compileQueryParser(val));355      break;356    case 'trust proxy':357      debug('compile trust proxy %s', val);358      this.set('trust proxy fn', compileTrust(val));359360      // trust proxy inherit back-compat361      Object.defineProperty(this.settings, trustProxyDefaultSymbol, {362        configurable: true,363        value: false364      });365366      break;367  }368369  return this;370};371372/**373 * Return the app's absolute pathname374 * based on the parent(s) that have375 * mounted it.376 *377 * For example if the application was378 * mounted as "/admin", which itself379 * was mounted as "/blog" then the380 * return value would be "/blog/admin".381 *382 * @return {String}383 * @api private384 */385386app.path = function(){387  return this.parent388    ? this.parent.path() + this.mountpath389    : '';390};391392/**393 * Check if `setting` is enabled (truthy).394 *395 *    app.enabled('foo')396 *    // => false397 *398 *    app.enable('foo')399 *    app.enabled('foo')400 *    // => true401 *402 * @param {String} setting403 * @return {Boolean}404 * @api public405 */406407app.enabled = function(setting){408  return !!this.set(setting);409};410411/**412 * Check if `setting` is disabled.413 *414 *    app.disabled('foo')415 *    // => true416 *417 *    app.enable('foo')418 *    app.disabled('foo')419 *    // => false420 *421 * @param {String} setting422 * @return {Boolean}423 * @api public424 */425426app.disabled = function(setting){427  return !this.set(setting);428};429430/**431 * Enable `setting`.432 *433 * @param {String} setting434 * @return {app} for chaining435 * @api public436 */437438app.enable = function(setting){439  return this.set(setting, true);440};441442/**443 * Disable `setting`.444 *445 * @param {String} setting446 * @return {app} for chaining447 * @api public448 */449450app.disable = function(setting){451  return this.set(setting, false);452};453454/**455 * Delegate `.VERB(...)` calls to `router.VERB(...)`.456 */457458methods.forEach(function(method){459  app[method] = function(path){460    if ('get' == method && 1 == arguments.length) return this.set(path);461462    this.lazyrouter();463464    var route = this._router.route(path);465    route[method].apply(route, slice.call(arguments, 1));466    return this;467  };468});469470/**471 * Special-cased "all" method, applying the given route `path`,472 * middleware, and callback to _every_ HTTP method.473 *474 * @param {String} path475 * @param {Function} ...476 * @return {app} for chaining477 * @api public478 */479480app.all = function(path){481  this.lazyrouter();482483  var route = this._router.route(path);484  var args = slice.call(arguments, 1);485  methods.forEach(function(method){486    route[method].apply(route, args);487  });488489  return this;490};491492// del -> delete alias493494app.del = deprecate.function(app.delete, 'app.del: Use app.delete instead');495496/**497 * Render the given view `name` name with `options`498 * and a callback accepting an error and the499 * rendered template string.500 *501 * Example:502 *503 *    app.render('email', { name: 'Tobi' }, function(err, html){504 *      // ...505 *    })506 *507 * @param {String} name508 * @param {String|Function} options or fn509 * @param {Function} fn510 * @api public511 */512513app.render = function(name, options, fn){514  var opts = {};515  var cache = this.cache;516  var engines = this.engines;517  var view;518519  // support callback function as second arg520  if ('function' == typeof options) {521    fn = options, options = {};522  }523524  // merge app.locals525  merge(opts, this.locals);526527  // merge options._locals528  if (options._locals) {529    merge(opts, options._locals);530  }531532  // merge options533  merge(opts, options);534535  // set .cache unless explicitly provided536  opts.cache = null == opts.cache537    ? this.enabled('view cache')538    : opts.cache;539540  // primed cache541  if (opts.cache) view = cache[name];542543  // view544  if (!view) {545    view = new (this.get('view'))(name, {546      defaultEngine: this.get('view engine'),547      root: this.get('views'),548      engines: engines549    });550551    if (!view.path) {552      var dirs = Array.isArray(view.root) && view.root.length > 1553        ? 'directories "' + view.root.slice(0, -1).join('", "') + '" or "' + view.root[view.root.length - 1] + '"'554        : 'directory "' + view.root + '"'555      var err = new Error('Failed to lookup view "' + name + '" in views ' + dirs);556      err.view = view;557      return fn(err);558    }559560    // prime the cache561    if (opts.cache) cache[name] = view;562  }563564  // render565  try {566    view.render(opts, fn);567  } catch (err) {568    fn(err);569  }570};571572/**573 * Listen for connections.574 *575 * A node `http.Server` is returned, with this576 * application (which is a `Function`) as its577 * callback. If you wish to create both an HTTP578 * and HTTPS server you may do so with the "http"579 * and "https" modules as shown here:580 *581 *    var http = require('http')582 *      , https = require('https')583 *      , express = require('express')584 *      , app = express();585 *586 *    http.createServer(app).listen(80);587 *    https.createServer({ ... }, app).listen(443);588 *589 * @return {http.Server}590 * @api public591 */592593app.listen = function(){594  var server = http.createServer(this);595  return server.listen.apply(server, arguments);596};597598/**599* Log error using console.error.600*601* @param {Error} err602* @api private603*/604605function logerror(err){606  if (this.get('env') !== 'test') console.error(err.stack || err.toString());607}