Skip to content
Myr

application.js

This file

Path

lib/application.js

661 lines · 14.3 KiB · JavaScript

Last changed by

Ignore Object.prototype values in settings through app.set/app.getEvan Hahnbefore adoptionc17fe05

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 * @private14 */1516var finalhandler = require('finalhandler');17var Router = require('./router');18var methods = require('methods');19var middleware = require('./middleware/init');20var query = require('./middleware/query');21var debug = require('debug')('express:application');22var View = require('./view');23var http = require('http');24var compileETag = require('./utils').compileETag;25var compileQueryParser = require('./utils').compileQueryParser;26var compileTrust = require('./utils').compileTrust;27var deprecate = require('depd')('express');28var flatten = require('array-flatten');29var merge = require('utils-merge');30var resolve = require('path').resolve;31var setPrototypeOf = require('setprototypeof')3233/**34 * Module variables.35 * @private36 */3738var hasOwnProperty = Object.prototype.hasOwnProperty39var slice = Array.prototype.slice;4041/**42 * Application prototype.43 */4445var app = exports = module.exports = {};4647/**48 * Variable for trust proxy inheritance back-compat49 * @private50 */5152var trustProxyDefaultSymbol = '@@symbol:trust_proxy_default';5354/**55 * Initialize the server.56 *57 *   - setup default configuration58 *   - setup default middleware59 *   - setup route reflection methods60 *61 * @private62 */6364app.init = function init() {65  this.cache = {};66  this.engines = {};67  this.settings = {};6869  this.defaultConfiguration();70};7172/**73 * Initialize application configuration.74 * @private75 */7677app.defaultConfiguration = function defaultConfiguration() {78  var env = process.env.NODE_ENV || 'development';7980  // default settings81  this.enable('x-powered-by');82  this.set('etag', 'weak');83  this.set('env', env);84  this.set('query parser', 'extended');85  this.set('subdomain offset', 2);86  this.set('trust proxy', false);8788  // trust proxy inherit back-compat89  Object.defineProperty(this.settings, trustProxyDefaultSymbol, {90    configurable: true,91    value: true92  });9394  debug('booting in %s mode', env);9596  this.on('mount', function onmount(parent) {97    // inherit trust proxy98    if (this.settings[trustProxyDefaultSymbol] === true99      && typeof parent.settings['trust proxy fn'] === 'function') {100      delete this.settings['trust proxy'];101      delete this.settings['trust proxy fn'];102    }103104    // inherit protos105    setPrototypeOf(this.request, parent.request)106    setPrototypeOf(this.response, parent.response)107    setPrototypeOf(this.engines, parent.engines)108    setPrototypeOf(this.settings, parent.settings)109  });110111  // setup locals112  this.locals = Object.create(null);113114  // top-most app is mounted at /115  this.mountpath = '/';116117  // default locals118  this.locals.settings = this.settings;119120  // default configuration121  this.set('view', View);122  this.set('views', resolve('views'));123  this.set('jsonp callback name', 'callback');124125  if (env === 'production') {126    this.enable('view cache');127  }128129  Object.defineProperty(this, 'router', {130    get: function() {131      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.');132    }133  });134};135136/**137 * lazily adds the base router if it has not yet been added.138 *139 * We cannot add the base router in the defaultConfiguration because140 * it reads app settings which might be set after that has run.141 *142 * @private143 */144app.lazyrouter = function lazyrouter() {145  if (!this._router) {146    this._router = new Router({147      caseSensitive: this.enabled('case sensitive routing'),148      strict: this.enabled('strict routing')149    });150151    this._router.use(query(this.get('query parser fn')));152    this._router.use(middleware.init(this));153  }154};155156/**157 * Dispatch a req, res pair into the application. Starts pipeline processing.158 *159 * If no callback is provided, then default error handlers will respond160 * in the event of an error bubbling through the stack.161 *162 * @private163 */164165app.handle = function handle(req, res, callback) {166  var router = this._router;167168  // final handler169  var done = callback || finalhandler(req, res, {170    env: this.get('env'),171    onerror: logerror.bind(this)172  });173174  // no routes175  if (!router) {176    debug('no routes defined on app');177    done();178    return;179  }180181  router.handle(req, res, done);182};183184/**185 * Proxy `Router#use()` to add middleware to the app router.186 * See Router#use() documentation for details.187 *188 * If the _fn_ parameter is an express app, then it will be189 * mounted at the _route_ specified.190 *191 * @public192 */193194app.use = function use(fn) {195  var offset = 0;196  var path = '/';197198  // default path to '/'199  // disambiguate app.use([fn])200  if (typeof fn !== 'function') {201    var arg = fn;202203    while (Array.isArray(arg) && arg.length !== 0) {204      arg = arg[0];205    }206207    // first arg is the path208    if (typeof arg !== 'function') {209      offset = 1;210      path = fn;211    }212  }213214  var fns = flatten(slice.call(arguments, offset));215216  if (fns.length === 0) {217    throw new TypeError('app.use() requires a middleware function')218  }219220  // setup router221  this.lazyrouter();222  var router = this._router;223224  fns.forEach(function (fn) {225    // non-express app226    if (!fn || !fn.handle || !fn.set) {227      return router.use(path, fn);228    }229230    debug('.use app under %s', path);231    fn.mountpath = path;232    fn.parent = this;233234    // restore .app property on req and res235    router.use(path, function mounted_app(req, res, next) {236      var orig = req.app;237      fn.handle(req, res, function (err) {238        setPrototypeOf(req, orig.request)239        setPrototypeOf(res, orig.response)240        next(err);241      });242    });243244    // mounted an app245    fn.emit('mount', this);246  }, this);247248  return this;249};250251/**252 * Proxy to the app `Router#route()`253 * Returns a new `Route` instance for the _path_.254 *255 * Routes are isolated middleware stacks for specific paths.256 * See the Route api docs for details.257 *258 * @public259 */260261app.route = function route(path) {262  this.lazyrouter();263  return this._router.route(path);264};265266/**267 * Register the given template engine callback `fn`268 * as `ext`.269 *270 * By default will `require()` the engine based on the271 * file extension. For example if you try to render272 * a "foo.ejs" file Express will invoke the following internally:273 *274 *     app.engine('ejs', require('ejs').__express);275 *276 * For engines that do not provide `.__express` out of the box,277 * or if you wish to "map" a different extension to the template engine278 * you may use this method. For example mapping the EJS template engine to279 * ".html" files:280 *281 *     app.engine('html', require('ejs').renderFile);282 *283 * In this case EJS provides a `.renderFile()` method with284 * the same signature that Express expects: `(path, options, callback)`,285 * though note that it aliases this method as `ejs.__express` internally286 * so if you're using ".ejs" extensions you don't need to do anything.287 *288 * Some template engines do not follow this convention, the289 * [Consolidate.js](https://github.com/tj/consolidate.js)290 * library was created to map all of node's popular template291 * engines to follow this convention, thus allowing them to292 * work seamlessly within Express.293 *294 * @param {String} ext295 * @param {Function} fn296 * @return {app} for chaining297 * @public298 */299300app.engine = function engine(ext, fn) {301  if (typeof fn !== 'function') {302    throw new Error('callback function required');303  }304305  // get file extension306  var extension = ext[0] !== '.'307    ? '.' + ext308    : ext;309310  // store engine311  this.engines[extension] = fn;312313  return this;314};315316/**317 * Proxy to `Router#param()` with one added api feature. The _name_ parameter318 * can be an array of names.319 *320 * See the Router#param() docs for more details.321 *322 * @param {String|Array} name323 * @param {Function} fn324 * @return {app} for chaining325 * @public326 */327328app.param = function param(name, fn) {329  this.lazyrouter();330331  if (Array.isArray(name)) {332    for (var i = 0; i < name.length; i++) {333      this.param(name[i], fn);334    }335336    return this;337  }338339  this._router.param(name, fn);340341  return this;342};343344/**345 * Assign `setting` to `val`, or return `setting`'s value.346 *347 *    app.set('foo', 'bar');348 *    app.set('foo');349 *    // => "bar"350 *351 * Mounted servers inherit their parent server's settings.352 *353 * @param {String} setting354 * @param {*} [val]355 * @return {Server} for chaining356 * @public357 */358359app.set = function set(setting, val) {360  if (arguments.length === 1) {361    // app.get(setting)362    var settings = this.settings363364    while (settings && settings !== Object.prototype) {365      if (hasOwnProperty.call(settings, setting)) {366        return settings[setting]367      }368369      settings = Object.getPrototypeOf(settings)370    }371372    return undefined373  }374375  debug('set "%s" to %o', setting, val);376377  // set value378  this.settings[setting] = val;379380  // trigger matched settings381  switch (setting) {382    case 'etag':383      this.set('etag fn', compileETag(val));384      break;385    case 'query parser':386      this.set('query parser fn', compileQueryParser(val));387      break;388    case 'trust proxy':389      this.set('trust proxy fn', compileTrust(val));390391      // trust proxy inherit back-compat392      Object.defineProperty(this.settings, trustProxyDefaultSymbol, {393        configurable: true,394        value: false395      });396397      break;398  }399400  return this;401};402403/**404 * Return the app's absolute pathname405 * based on the parent(s) that have406 * mounted it.407 *408 * For example if the application was409 * mounted as "/admin", which itself410 * was mounted as "/blog" then the411 * return value would be "/blog/admin".412 *413 * @return {String}414 * @private415 */416417app.path = function path() {418  return this.parent419    ? this.parent.path() + this.mountpath420    : '';421};422423/**424 * Check if `setting` is enabled (truthy).425 *426 *    app.enabled('foo')427 *    // => false428 *429 *    app.enable('foo')430 *    app.enabled('foo')431 *    // => true432 *433 * @param {String} setting434 * @return {Boolean}435 * @public436 */437438app.enabled = function enabled(setting) {439  return Boolean(this.set(setting));440};441442/**443 * Check if `setting` is disabled.444 *445 *    app.disabled('foo')446 *    // => true447 *448 *    app.enable('foo')449 *    app.disabled('foo')450 *    // => false451 *452 * @param {String} setting453 * @return {Boolean}454 * @public455 */456457app.disabled = function disabled(setting) {458  return !this.set(setting);459};460461/**462 * Enable `setting`.463 *464 * @param {String} setting465 * @return {app} for chaining466 * @public467 */468469app.enable = function enable(setting) {470  return this.set(setting, true);471};472473/**474 * Disable `setting`.475 *476 * @param {String} setting477 * @return {app} for chaining478 * @public479 */480481app.disable = function disable(setting) {482  return this.set(setting, false);483};484485/**486 * Delegate `.VERB(...)` calls to `router.VERB(...)`.487 */488489methods.forEach(function(method){490  app[method] = function(path){491    if (method === 'get' && arguments.length === 1) {492      // app.get(setting)493      return this.set(path);494    }495496    this.lazyrouter();497498    var route = this._router.route(path);499    route[method].apply(route, slice.call(arguments, 1));500    return this;501  };502});503504/**505 * Special-cased "all" method, applying the given route `path`,506 * middleware, and callback to _every_ HTTP method.507 *508 * @param {String} path509 * @param {Function} ...510 * @return {app} for chaining511 * @public512 */513514app.all = function all(path) {515  this.lazyrouter();516517  var route = this._router.route(path);518  var args = slice.call(arguments, 1);519520  for (var i = 0; i < methods.length; i++) {521    route[methods[i]].apply(route, args);522  }523524  return this;525};526527// del -> delete alias528529app.del = deprecate.function(app.delete, 'app.del: Use app.delete instead');530531/**532 * Render the given view `name` name with `options`533 * and a callback accepting an error and the534 * rendered template string.535 *536 * Example:537 *538 *    app.render('email', { name: 'Tobi' }, function(err, html){539 *      // ...540 *    })541 *542 * @param {String} name543 * @param {Object|Function} options or fn544 * @param {Function} callback545 * @public546 */547548app.render = function render(name, options, callback) {549  var cache = this.cache;550  var done = callback;551  var engines = this.engines;552  var opts = options;553  var renderOptions = {};554  var view;555556  // support callback function as second arg557  if (typeof options === 'function') {558    done = options;559    opts = {};560  }561562  // merge app.locals563  merge(renderOptions, this.locals);564565  // merge options._locals566  if (opts._locals) {567    merge(renderOptions, opts._locals);568  }569570  // merge options571  merge(renderOptions, opts);572573  // set .cache unless explicitly provided574  if (renderOptions.cache == null) {575    renderOptions.cache = this.enabled('view cache');576  }577578  // primed cache579  if (renderOptions.cache) {580    view = cache[name];581  }582583  // view584  if (!view) {585    var View = this.get('view');586587    view = new View(name, {588      defaultEngine: this.get('view engine'),589      root: this.get('views'),590      engines: engines591    });592593    if (!view.path) {594      var dirs = Array.isArray(view.root) && view.root.length > 1595        ? 'directories "' + view.root.slice(0, -1).join('", "') + '" or "' + view.root[view.root.length - 1] + '"'596        : 'directory "' + view.root + '"'597      var err = new Error('Failed to lookup view "' + name + '" in views ' + dirs);598      err.view = view;599      return done(err);600    }601602    // prime the cache603    if (renderOptions.cache) {604      cache[name] = view;605    }606  }607608  // render609  tryRender(view, renderOptions, done);610};611612/**613 * Listen for connections.614 *615 * A node `http.Server` is returned, with this616 * application (which is a `Function`) as its617 * callback. If you wish to create both an HTTP618 * and HTTPS server you may do so with the "http"619 * and "https" modules as shown here:620 *621 *    var http = require('http')622 *      , https = require('https')623 *      , express = require('express')624 *      , app = express();625 *626 *    http.createServer(app).listen(80);627 *    https.createServer({ ... }, app).listen(443);628 *629 * @return {http.Server}630 * @public631 */632633app.listen = function listen() {634  var server = http.createServer(this);635  return server.listen.apply(server, arguments);636};637638/**639 * Log error using console.error.640 *641 * @param {Error} err642 * @private643 */644645function logerror(err) {646  /* istanbul ignore next */647  if (this.get('env') !== 'test') console.error(err.stack || err.toString());648}649650/**651 * Try rendering a view.652 * @private653 */654655function tryRender(view, options, callback) {656  try {657    view.render(options, callback);658  } catch (err) {659    callback(err);660  }661}