Skip to content
Myr

application.js

This file

Path

lib/application.js

644 lines · 13.9 KiB · JavaScript

Last changed by

Fix typo in variable name setPrototypeOfasaf davidbefore adoptionc087a45

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')32var slice = Array.prototype.slice;3334/**35 * Application prototype.36 */3738var app = exports = module.exports = {};3940/**41 * Variable for trust proxy inheritance back-compat42 * @private43 */4445var trustProxyDefaultSymbol = '@@symbol:trust_proxy_default';4647/**48 * Initialize the server.49 *50 *   - setup default configuration51 *   - setup default middleware52 *   - setup route reflection methods53 *54 * @private55 */5657app.init = function init() {58  this.cache = {};59  this.engines = {};60  this.settings = {};6162  this.defaultConfiguration();63};6465/**66 * Initialize application configuration.67 * @private68 */6970app.defaultConfiguration = function defaultConfiguration() {71  var env = process.env.NODE_ENV || 'development';7273  // default settings74  this.enable('x-powered-by');75  this.set('etag', 'weak');76  this.set('env', env);77  this.set('query parser', 'extended');78  this.set('subdomain offset', 2);79  this.set('trust proxy', false);8081  // trust proxy inherit back-compat82  Object.defineProperty(this.settings, trustProxyDefaultSymbol, {83    configurable: true,84    value: true85  });8687  debug('booting in %s mode', env);8889  this.on('mount', function onmount(parent) {90    // inherit trust proxy91    if (this.settings[trustProxyDefaultSymbol] === true92      && typeof parent.settings['trust proxy fn'] === 'function') {93      delete this.settings['trust proxy'];94      delete this.settings['trust proxy fn'];95    }9697    // inherit protos98    setPrototypeOf(this.request, parent.request)99    setPrototypeOf(this.response, parent.response)100    setPrototypeOf(this.engines, parent.engines)101    setPrototypeOf(this.settings, parent.settings)102  });103104  // setup locals105  this.locals = Object.create(null);106107  // top-most app is mounted at /108  this.mountpath = '/';109110  // default locals111  this.locals.settings = this.settings;112113  // default configuration114  this.set('view', View);115  this.set('views', resolve('views'));116  this.set('jsonp callback name', 'callback');117118  if (env === 'production') {119    this.enable('view cache');120  }121122  Object.defineProperty(this, 'router', {123    get: function() {124      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.');125    }126  });127};128129/**130 * lazily adds the base router if it has not yet been added.131 *132 * We cannot add the base router in the defaultConfiguration because133 * it reads app settings which might be set after that has run.134 *135 * @private136 */137app.lazyrouter = function lazyrouter() {138  if (!this._router) {139    this._router = new Router({140      caseSensitive: this.enabled('case sensitive routing'),141      strict: this.enabled('strict routing')142    });143144    this._router.use(query(this.get('query parser fn')));145    this._router.use(middleware.init(this));146  }147};148149/**150 * Dispatch a req, res pair into the application. Starts pipeline processing.151 *152 * If no callback is provided, then default error handlers will respond153 * in the event of an error bubbling through the stack.154 *155 * @private156 */157158app.handle = function handle(req, res, callback) {159  var router = this._router;160161  // final handler162  var done = callback || finalhandler(req, res, {163    env: this.get('env'),164    onerror: logerror.bind(this)165  });166167  // no routes168  if (!router) {169    debug('no routes defined on app');170    done();171    return;172  }173174  router.handle(req, res, done);175};176177/**178 * Proxy `Router#use()` to add middleware to the app router.179 * See Router#use() documentation for details.180 *181 * If the _fn_ parameter is an express app, then it will be182 * mounted at the _route_ specified.183 *184 * @public185 */186187app.use = function use(fn) {188  var offset = 0;189  var path = '/';190191  // default path to '/'192  // disambiguate app.use([fn])193  if (typeof fn !== 'function') {194    var arg = fn;195196    while (Array.isArray(arg) && arg.length !== 0) {197      arg = arg[0];198    }199200    // first arg is the path201    if (typeof arg !== 'function') {202      offset = 1;203      path = fn;204    }205  }206207  var fns = flatten(slice.call(arguments, offset));208209  if (fns.length === 0) {210    throw new TypeError('app.use() requires middleware functions');211  }212213  // setup router214  this.lazyrouter();215  var router = this._router;216217  fns.forEach(function (fn) {218    // non-express app219    if (!fn || !fn.handle || !fn.set) {220      return router.use(path, fn);221    }222223    debug('.use app under %s', path);224    fn.mountpath = path;225    fn.parent = this;226227    // restore .app property on req and res228    router.use(path, function mounted_app(req, res, next) {229      var orig = req.app;230      fn.handle(req, res, function (err) {231        setPrototypeOf(req, orig.request)232        setPrototypeOf(res, orig.response)233        next(err);234      });235    });236237    // mounted an app238    fn.emit('mount', this);239  }, this);240241  return this;242};243244/**245 * Proxy to the app `Router#route()`246 * Returns a new `Route` instance for the _path_.247 *248 * Routes are isolated middleware stacks for specific paths.249 * See the Route api docs for details.250 *251 * @public252 */253254app.route = function route(path) {255  this.lazyrouter();256  return this._router.route(path);257};258259/**260 * Register the given template engine callback `fn`261 * as `ext`.262 *263 * By default will `require()` the engine based on the264 * file extension. For example if you try to render265 * a "foo.ejs" file Express will invoke the following internally:266 *267 *     app.engine('ejs', require('ejs').__express);268 *269 * For engines that do not provide `.__express` out of the box,270 * or if you wish to "map" a different extension to the template engine271 * you may use this method. For example mapping the EJS template engine to272 * ".html" files:273 *274 *     app.engine('html', require('ejs').renderFile);275 *276 * In this case EJS provides a `.renderFile()` method with277 * the same signature that Express expects: `(path, options, callback)`,278 * though note that it aliases this method as `ejs.__express` internally279 * so if you're using ".ejs" extensions you dont need to do anything.280 *281 * Some template engines do not follow this convention, the282 * [Consolidate.js](https://github.com/tj/consolidate.js)283 * library was created to map all of node's popular template284 * engines to follow this convention, thus allowing them to285 * work seamlessly within Express.286 *287 * @param {String} ext288 * @param {Function} fn289 * @return {app} for chaining290 * @public291 */292293app.engine = function engine(ext, fn) {294  if (typeof fn !== 'function') {295    throw new Error('callback function required');296  }297298  // get file extension299  var extension = ext[0] !== '.'300    ? '.' + ext301    : ext;302303  // store engine304  this.engines[extension] = fn;305306  return this;307};308309/**310 * Proxy to `Router#param()` with one added api feature. The _name_ parameter311 * can be an array of names.312 *313 * See the Router#param() docs for more details.314 *315 * @param {String|Array} name316 * @param {Function} fn317 * @return {app} for chaining318 * @public319 */320321app.param = function param(name, fn) {322  this.lazyrouter();323324  if (Array.isArray(name)) {325    for (var i = 0; i < name.length; i++) {326      this.param(name[i], fn);327    }328329    return this;330  }331332  this._router.param(name, fn);333334  return this;335};336337/**338 * Assign `setting` to `val`, or return `setting`'s value.339 *340 *    app.set('foo', 'bar');341 *    app.get('foo');342 *    // => "bar"343 *344 * Mounted servers inherit their parent server's settings.345 *346 * @param {String} setting347 * @param {*} [val]348 * @return {Server} for chaining349 * @public350 */351352app.set = function set(setting, val) {353  if (arguments.length === 1) {354    // app.get(setting)355    return this.settings[setting];356  }357358  debug('set "%s" to %o', setting, val);359360  // set value361  this.settings[setting] = val;362363  // trigger matched settings364  switch (setting) {365    case 'etag':366      this.set('etag fn', compileETag(val));367      break;368    case 'query parser':369      this.set('query parser fn', compileQueryParser(val));370      break;371    case 'trust proxy':372      this.set('trust proxy fn', compileTrust(val));373374      // trust proxy inherit back-compat375      Object.defineProperty(this.settings, trustProxyDefaultSymbol, {376        configurable: true,377        value: false378      });379380      break;381  }382383  return this;384};385386/**387 * Return the app's absolute pathname388 * based on the parent(s) that have389 * mounted it.390 *391 * For example if the application was392 * mounted as "/admin", which itself393 * was mounted as "/blog" then the394 * return value would be "/blog/admin".395 *396 * @return {String}397 * @private398 */399400app.path = function path() {401  return this.parent402    ? this.parent.path() + this.mountpath403    : '';404};405406/**407 * Check if `setting` is enabled (truthy).408 *409 *    app.enabled('foo')410 *    // => false411 *412 *    app.enable('foo')413 *    app.enabled('foo')414 *    // => true415 *416 * @param {String} setting417 * @return {Boolean}418 * @public419 */420421app.enabled = function enabled(setting) {422  return Boolean(this.set(setting));423};424425/**426 * Check if `setting` is disabled.427 *428 *    app.disabled('foo')429 *    // => true430 *431 *    app.enable('foo')432 *    app.disabled('foo')433 *    // => false434 *435 * @param {String} setting436 * @return {Boolean}437 * @public438 */439440app.disabled = function disabled(setting) {441  return !this.set(setting);442};443444/**445 * Enable `setting`.446 *447 * @param {String} setting448 * @return {app} for chaining449 * @public450 */451452app.enable = function enable(setting) {453  return this.set(setting, true);454};455456/**457 * Disable `setting`.458 *459 * @param {String} setting460 * @return {app} for chaining461 * @public462 */463464app.disable = function disable(setting) {465  return this.set(setting, false);466};467468/**469 * Delegate `.VERB(...)` calls to `router.VERB(...)`.470 */471472methods.forEach(function(method){473  app[method] = function(path){474    if (method === 'get' && arguments.length === 1) {475      // app.get(setting)476      return this.set(path);477    }478479    this.lazyrouter();480481    var route = this._router.route(path);482    route[method].apply(route, slice.call(arguments, 1));483    return this;484  };485});486487/**488 * Special-cased "all" method, applying the given route `path`,489 * middleware, and callback to _every_ HTTP method.490 *491 * @param {String} path492 * @param {Function} ...493 * @return {app} for chaining494 * @public495 */496497app.all = function all(path) {498  this.lazyrouter();499500  var route = this._router.route(path);501  var args = slice.call(arguments, 1);502503  for (var i = 0; i < methods.length; i++) {504    route[methods[i]].apply(route, args);505  }506507  return this;508};509510// del -> delete alias511512app.del = deprecate.function(app.delete, 'app.del: Use app.delete instead');513514/**515 * Render the given view `name` name with `options`516 * and a callback accepting an error and the517 * rendered template string.518 *519 * Example:520 *521 *    app.render('email', { name: 'Tobi' }, function(err, html){522 *      // ...523 *    })524 *525 * @param {String} name526 * @param {Object|Function} options or fn527 * @param {Function} callback528 * @public529 */530531app.render = function render(name, options, callback) {532  var cache = this.cache;533  var done = callback;534  var engines = this.engines;535  var opts = options;536  var renderOptions = {};537  var view;538539  // support callback function as second arg540  if (typeof options === 'function') {541    done = options;542    opts = {};543  }544545  // merge app.locals546  merge(renderOptions, this.locals);547548  // merge options._locals549  if (opts._locals) {550    merge(renderOptions, opts._locals);551  }552553  // merge options554  merge(renderOptions, opts);555556  // set .cache unless explicitly provided557  if (renderOptions.cache == null) {558    renderOptions.cache = this.enabled('view cache');559  }560561  // primed cache562  if (renderOptions.cache) {563    view = cache[name];564  }565566  // view567  if (!view) {568    var View = this.get('view');569570    view = new View(name, {571      defaultEngine: this.get('view engine'),572      root: this.get('views'),573      engines: engines574    });575576    if (!view.path) {577      var dirs = Array.isArray(view.root) && view.root.length > 1578        ? 'directories "' + view.root.slice(0, -1).join('", "') + '" or "' + view.root[view.root.length - 1] + '"'579        : 'directory "' + view.root + '"'580      var err = new Error('Failed to lookup view "' + name + '" in views ' + dirs);581      err.view = view;582      return done(err);583    }584585    // prime the cache586    if (renderOptions.cache) {587      cache[name] = view;588    }589  }590591  // render592  tryRender(view, renderOptions, done);593};594595/**596 * Listen for connections.597 *598 * A node `http.Server` is returned, with this599 * application (which is a `Function`) as its600 * callback. If you wish to create both an HTTP601 * and HTTPS server you may do so with the "http"602 * and "https" modules as shown here:603 *604 *    var http = require('http')605 *      , https = require('https')606 *      , express = require('express')607 *      , app = express();608 *609 *    http.createServer(app).listen(80);610 *    https.createServer({ ... }, app).listen(443);611 *612 * @return {http.Server}613 * @public614 */615616app.listen = function listen() {617  var server = http.createServer(this);618  return server.listen.apply(server, arguments);619};620621/**622 * Log error using console.error.623 *624 * @param {Error} err625 * @private626 */627628function logerror(err) {629  /* istanbul ignore next */630  if (this.get('env') !== 'test') console.error(err.stack || err.toString());631}632633/**634 * Try rendering a view.635 * @private636 */637638function tryRender(view, options, callback) {639  try {640    view.render(options, callback);641  } catch (err) {642    callback(err);643  }644}