Skip to content
Myr

application.js

This file

Path

lib/application.js

641 lines · 13.8 KiB · JavaScript

Last changed by

refactor: Remove Object.setPrototypeOf polyfill (#6081)Phillip Bartabefore adoption8cb53ea

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 methods = require('methods');18var debug = require('debug')('express:application');19var View = require('./view');20var http = require('http');21var compileETag = require('./utils').compileETag;22var compileQueryParser = require('./utils').compileQueryParser;23var compileTrust = require('./utils').compileTrust;24var merge = require('utils-merge');25var resolve = require('path').resolve;26var once = require('once')27var Router = require('router');2829/**30 * Module variables.31 * @private32 */3334var slice = Array.prototype.slice;35var flatten = Array.prototype.flat;3637/**38 * Application prototype.39 */4041var app = exports = module.exports = {};4243/**44 * Variable for trust proxy inheritance back-compat45 * @private46 */4748var trustProxyDefaultSymbol = '@@symbol:trust_proxy_default';4950/**51 * Initialize the server.52 *53 *   - setup default configuration54 *   - setup default middleware55 *   - setup route reflection methods56 *57 * @private58 */5960app.init = function init() {61  var router = null;6263  this.cache = Object.create(null);64  this.engines = Object.create(null);65  this.settings = Object.create(null);6667  this.defaultConfiguration();6869  // Setup getting to lazily add base router70  Object.defineProperty(this, 'router', {71    configurable: true,72    enumerable: true,73    get: function getrouter() {74      if (router === null) {75        router = new Router({76          caseSensitive: this.enabled('case sensitive routing'),77          strict: this.enabled('strict routing')78        });79      }8081      return router;82    }83  });84};8586/**87 * Initialize application configuration.88 * @private89 */9091app.defaultConfiguration = function defaultConfiguration() {92  var env = process.env.NODE_ENV || 'development';9394  // default settings95  this.enable('x-powered-by');96  this.set('etag', 'weak');97  this.set('env', env);98  this.set('query parser', 'simple')99  this.set('subdomain offset', 2);100  this.set('trust proxy', false);101102  // trust proxy inherit back-compat103  Object.defineProperty(this.settings, trustProxyDefaultSymbol, {104    configurable: true,105    value: true106  });107108  debug('booting in %s mode', env);109110  this.on('mount', function onmount(parent) {111    // inherit trust proxy112    if (this.settings[trustProxyDefaultSymbol] === true113      && typeof parent.settings['trust proxy fn'] === 'function') {114      delete this.settings['trust proxy'];115      delete this.settings['trust proxy fn'];116    }117118    // inherit protos119    Object.setPrototypeOf(this.request, parent.request)120    Object.setPrototypeOf(this.response, parent.response)121    Object.setPrototypeOf(this.engines, parent.engines)122    Object.setPrototypeOf(this.settings, parent.settings)123  });124125  // setup locals126  this.locals = Object.create(null);127128  // top-most app is mounted at /129  this.mountpath = '/';130131  // default locals132  this.locals.settings = this.settings;133134  // default configuration135  this.set('view', View);136  this.set('views', resolve('views'));137  this.set('jsonp callback name', 'callback');138139  if (env === 'production') {140    this.enable('view cache');141  }142};143144/**145 * Dispatch a req, res pair into the application. Starts pipeline processing.146 *147 * If no callback is provided, then default error handlers will respond148 * in the event of an error bubbling through the stack.149 *150 * @private151 */152153app.handle = function handle(req, res, callback) {154  // final handler155  var done = callback || finalhandler(req, res, {156    env: this.get('env'),157    onerror: logerror.bind(this)158  });159160  // set powered by header161  if (this.enabled('x-powered-by')) {162    res.setHeader('X-Powered-By', 'Express');163  }164165  // set circular references166  req.res = res;167  res.req = req;168169  // alter the prototypes170  Object.setPrototypeOf(req, this.request)171  Object.setPrototypeOf(res, this.response)172173  // setup locals174  if (!res.locals) {175    res.locals = Object.create(null);176  }177178  this.router.handle(req, res, done);179};180181/**182 * Proxy `Router#use()` to add middleware to the app router.183 * See Router#use() documentation for details.184 *185 * If the _fn_ parameter is an express app, then it will be186 * mounted at the _route_ specified.187 *188 * @public189 */190191app.use = function use(fn) {192  var offset = 0;193  var path = '/';194195  // default path to '/'196  // disambiguate app.use([fn])197  if (typeof fn !== 'function') {198    var arg = fn;199200    while (Array.isArray(arg) && arg.length !== 0) {201      arg = arg[0];202    }203204    // first arg is the path205    if (typeof arg !== 'function') {206      offset = 1;207      path = fn;208    }209  }210211  var fns = flatten.call(slice.call(arguments, offset), Infinity);212213  if (fns.length === 0) {214    throw new TypeError('app.use() requires a middleware function')215  }216217  // get router218  var router = this.router;219220  fns.forEach(function (fn) {221    // non-express app222    if (!fn || !fn.handle || !fn.set) {223      return router.use(path, fn);224    }225226    debug('.use app under %s', path);227    fn.mountpath = path;228    fn.parent = this;229230    // restore .app property on req and res231    router.use(path, function mounted_app(req, res, next) {232      var orig = req.app;233      fn.handle(req, res, function (err) {234        Object.setPrototypeOf(req, orig.request)235        Object.setPrototypeOf(res, orig.response)236        next(err);237      });238    });239240    // mounted an app241    fn.emit('mount', this);242  }, this);243244  return this;245};246247/**248 * Proxy to the app `Router#route()`249 * Returns a new `Route` instance for the _path_.250 *251 * Routes are isolated middleware stacks for specific paths.252 * See the Route api docs for details.253 *254 * @public255 */256257app.route = function route(path) {258  return this.router.route(path);259};260261/**262 * Register the given template engine callback `fn`263 * as `ext`.264 *265 * By default will `require()` the engine based on the266 * file extension. For example if you try to render267 * a "foo.ejs" file Express will invoke the following internally:268 *269 *     app.engine('ejs', require('ejs').__express);270 *271 * For engines that do not provide `.__express` out of the box,272 * or if you wish to "map" a different extension to the template engine273 * you may use this method. For example mapping the EJS template engine to274 * ".html" files:275 *276 *     app.engine('html', require('ejs').renderFile);277 *278 * In this case EJS provides a `.renderFile()` method with279 * the same signature that Express expects: `(path, options, callback)`,280 * though note that it aliases this method as `ejs.__express` internally281 * so if you're using ".ejs" extensions you don't need to do anything.282 *283 * Some template engines do not follow this convention, the284 * [Consolidate.js](https://github.com/tj/consolidate.js)285 * library was created to map all of node's popular template286 * engines to follow this convention, thus allowing them to287 * work seamlessly within Express.288 *289 * @param {String} ext290 * @param {Function} fn291 * @return {app} for chaining292 * @public293 */294295app.engine = function engine(ext, fn) {296  if (typeof fn !== 'function') {297    throw new Error('callback function required');298  }299300  // get file extension301  var extension = ext[0] !== '.'302    ? '.' + ext303    : ext;304305  // store engine306  this.engines[extension] = fn;307308  return this;309};310311/**312 * Proxy to `Router#param()` with one added api feature. The _name_ parameter313 * can be an array of names.314 *315 * See the Router#param() docs for more details.316 *317 * @param {String|Array} name318 * @param {Function} fn319 * @return {app} for chaining320 * @public321 */322323app.param = function param(name, fn) {324  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.set('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    var route = this.route(path);480    route[method].apply(route, slice.call(arguments, 1));481    return this;482  };483});484485/**486 * Special-cased "all" method, applying the given route `path`,487 * middleware, and callback to _every_ HTTP method.488 *489 * @param {String} path490 * @param {Function} ...491 * @return {app} for chaining492 * @public493 */494495app.all = function all(path) {496  var route = this.route(path);497  var args = slice.call(arguments, 1);498499  for (var i = 0; i < methods.length; i++) {500    route[methods[i]].apply(route, args);501  }502503  return this;504};505506/**507 * Render the given view `name` name with `options`508 * and a callback accepting an error and the509 * rendered template string.510 *511 * Example:512 *513 *    app.render('email', { name: 'Tobi' }, function(err, html){514 *      // ...515 *    })516 *517 * @param {String} name518 * @param {Object|Function} options or fn519 * @param {Function} callback520 * @public521 */522523app.render = function render(name, options, callback) {524  var cache = this.cache;525  var done = callback;526  var engines = this.engines;527  var opts = options;528  var renderOptions = {};529  var view;530531  // support callback function as second arg532  if (typeof options === 'function') {533    done = options;534    opts = {};535  }536537  // merge app.locals538  merge(renderOptions, this.locals);539540  // merge options._locals541  if (opts._locals) {542    merge(renderOptions, opts._locals);543  }544545  // merge options546  merge(renderOptions, opts);547548  // set .cache unless explicitly provided549  if (renderOptions.cache == null) {550    renderOptions.cache = this.enabled('view cache');551  }552553  // primed cache554  if (renderOptions.cache) {555    view = cache[name];556  }557558  // view559  if (!view) {560    var View = this.get('view');561562    view = new View(name, {563      defaultEngine: this.get('view engine'),564      root: this.get('views'),565      engines: engines566    });567568    if (!view.path) {569      var dirs = Array.isArray(view.root) && view.root.length > 1570        ? 'directories "' + view.root.slice(0, -1).join('", "') + '" or "' + view.root[view.root.length - 1] + '"'571        : 'directory "' + view.root + '"'572      var err = new Error('Failed to lookup view "' + name + '" in views ' + dirs);573      err.view = view;574      return done(err);575    }576577    // prime the cache578    if (renderOptions.cache) {579      cache[name] = view;580    }581  }582583  // render584  tryRender(view, renderOptions, done);585};586587/**588 * Listen for connections.589 *590 * A node `http.Server` is returned, with this591 * application (which is a `Function`) as its592 * callback. If you wish to create both an HTTP593 * and HTTPS server you may do so with the "http"594 * and "https" modules as shown here:595 *596 *    var http = require('http')597 *      , https = require('https')598 *      , express = require('express')599 *      , app = express();600 *601 *    http.createServer(app).listen(80);602 *    https.createServer({ ... }, app).listen(443);603 *604 * @return {http.Server}605 * @public606 */607608app.listen = function listen () {609  var server = http.createServer(this)610  var args = Array.prototype.slice.call(arguments)611  if (typeof args[args.length - 1] === 'function') {612    var done = args[args.length - 1] = once(args[args.length - 1])613    server.once('error', done)614  }615  return server.listen.apply(server, args)616}617618/**619 * Log error using console.error.620 *621 * @param {Error} err622 * @private623 */624625function logerror(err) {626  /* istanbul ignore next */627  if (this.get('env') !== 'test') console.error(err.stack || err.toString());628}629630/**631 * Try rendering a view.632 * @private633 */634635function tryRender(view, options, callback) {636  try {637    view.render(options, callback);638  } catch (err) {639    callback(err);640  }641}