Skip to content
Myr

application.js

This file

Path

lib/application.js

554 lines · 12.1 KiB · JavaScript

Last changed by

Add configurable query parserDouglas Christopher Wilsonbefore adoptione29fa25

History of this file

Take it

1/**2 * Module dependencies.3 */45var finalhandler = require('finalhandler');6var mixin = require('utils-merge');7var Router = require('./router');8var methods = require('methods');9var middleware = require('./middleware/init');10var query = require('./middleware/query');11var debug = require('debug')('express:application');12var View = require('./view');13var http = require('http');14var compileETag = require('./utils').compileETag;15var compileQueryParser = require('./utils').compileQueryParser;16var compileTrust = require('./utils').compileTrust;17var deprecate = require('depd')('express');18var resolve = require('path').resolve;1920/**21 * Application prototype.22 */2324var app = exports = module.exports = {};2526/**27 * Initialize the server.28 *29 *   - setup default configuration30 *   - setup default middleware31 *   - setup route reflection methods32 *33 * @api private34 */3536app.init = function(){37  this.cache = {};38  this.settings = {};39  this.engines = {};40  this.defaultConfiguration();41};4243/**44 * Initialize application configuration.45 *46 * @api private47 */4849app.defaultConfiguration = function(){50  // default settings51  this.enable('x-powered-by');52  this.set('etag', 'weak');53  var env = process.env.NODE_ENV || 'development';54  this.set('env', env);55  this.set('query parser', 'extended');56  this.set('subdomain offset', 2);57  this.set('trust proxy', false);5859  debug('booting in %s mode', env);6061  // inherit protos62  this.on('mount', function(parent){63    this.request.__proto__ = parent.request;64    this.response.__proto__ = parent.response;65    this.engines.__proto__ = parent.engines;66    this.settings.__proto__ = parent.settings;67  });6869  // setup locals70  this.locals = Object.create(null);7172  // top-most app is mounted at /73  this.mountpath = '/';7475  // default locals76  this.locals.settings = this.settings;7778  // default configuration79  this.set('view', View);80  this.set('views', resolve('views'));81  this.set('jsonp callback name', 'callback');8283  if (env === 'production') {84    this.enable('view cache');85  }8687  Object.defineProperty(this, 'router', {88    get: function() {89      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.');90    }91  });92};9394/**95 * lazily adds the base router if it has not yet been added.96 *97 * We cannot add the base router in the defaultConfiguration because98 * it reads app settings which might be set after that has run.99 *100 * @api private101 */102app.lazyrouter = function() {103  if (!this._router) {104    this._router = new Router({105      caseSensitive: this.enabled('case sensitive routing'),106      strict: this.enabled('strict routing')107    });108109    this._router.use(query(this.get('query parser fn')));110    this._router.use(middleware.init(this));111  }112};113114/**115 * Dispatch a req, res pair into the application. Starts pipeline processing.116 *117 * If no _done_ callback is provided, then default error handlers will respond118 * in the event of an error bubbling through the stack.119 *120 * @api private121 */122123app.handle = function(req, res, done) {124  var router = this._router;125126  // final handler127  done = done || finalhandler(req, res, {128    env: this.get('env'),129    onerror: logerror.bind(this)130  });131132  // no routes133  if (!router) {134    debug('no routes defined on app');135    done();136    return;137  }138139  router.handle(req, res, done);140};141142/**143 * Proxy `Router#use()` to add middleware to the app router.144 * See Router#use() documentation for details.145 *146 * If the _fn_ parameter is an express app, then it will be147 * mounted at the _route_ specified.148 *149 * @api public150 */151152app.use = function use(path, fn) {153  var mount_app;154  var mount_path;155156  // check for .use(path, app) or .use(app) signature157  if (arguments.length <= 2) {158    mount_path = typeof path === 'string'159      ? path160      : '/';161    mount_app = typeof path === 'function'162      ? path163      : fn;164  }165166  // setup router167  this.lazyrouter();168  var router = this._router;169170  // express app171  if (mount_app && mount_app.handle && mount_app.set) {172    debug('.use app under %s', mount_path);173    mount_app.mountpath = mount_path;174    mount_app.parent = this;175176    // restore .app property on req and res177    router.use(mount_path, function mounted_app(req, res, next) {178      var orig = req.app;179      mount_app.handle(req, res, function(err) {180        req.__proto__ = orig.request;181        res.__proto__ = orig.response;182        next(err);183      });184    });185186    // mounted an app187    mount_app.emit('mount', this);188189    return this;190  }191192  // pass-through use193  router.use.apply(router, arguments);194195  return this;196};197198/**199 * Proxy to the app `Router#route()`200 * Returns a new `Route` instance for the _path_.201 *202 * Routes are isolated middleware stacks for specific paths.203 * See the Route api docs for details.204 *205 * @api public206 */207208app.route = function(path){209  this.lazyrouter();210  return this._router.route(path);211};212213/**214 * Register the given template engine callback `fn`215 * as `ext`.216 *217 * By default will `require()` the engine based on the218 * file extension. For example if you try to render219 * a "foo.jade" file Express will invoke the following internally:220 *221 *     app.engine('jade', require('jade').__express);222 *223 * For engines that do not provide `.__express` out of the box,224 * or if you wish to "map" a different extension to the template engine225 * you may use this method. For example mapping the EJS template engine to226 * ".html" files:227 *228 *     app.engine('html', require('ejs').renderFile);229 *230 * In this case EJS provides a `.renderFile()` method with231 * the same signature that Express expects: `(path, options, callback)`,232 * though note that it aliases this method as `ejs.__express` internally233 * so if you're using ".ejs" extensions you dont need to do anything.234 *235 * Some template engines do not follow this convention, the236 * [Consolidate.js](https://github.com/visionmedia/consolidate.js)237 * library was created to map all of node's popular template238 * engines to follow this convention, thus allowing them to239 * work seamlessly within Express.240 *241 * @param {String} ext242 * @param {Function} fn243 * @return {app} for chaining244 * @api public245 */246247app.engine = function(ext, fn){248  if ('function' != typeof fn) throw new Error('callback function required');249  if ('.' != ext[0]) ext = '.' + ext;250  this.engines[ext] = fn;251  return this;252};253254/**255 * Proxy to `Router#param()` with one added api feature. The _name_ parameter256 * can be an array of names.257 *258 * See the Router#param() docs for more details.259 *260 * @param {String|Array} name261 * @param {Function} fn262 * @return {app} for chaining263 * @api public264 */265266app.param = function(name, fn){267  var self = this;268  self.lazyrouter();269270  if (Array.isArray(name)) {271    name.forEach(function(key) {272      self.param(key, fn);273    });274    return this;275  }276277  self._router.param(name, fn);278  return this;279};280281/**282 * Assign `setting` to `val`, or return `setting`'s value.283 *284 *    app.set('foo', 'bar');285 *    app.get('foo');286 *    // => "bar"287 *288 * Mounted servers inherit their parent server's settings.289 *290 * @param {String} setting291 * @param {*} [val]292 * @return {Server} for chaining293 * @api public294 */295296app.set = function(setting, val){297  if (arguments.length === 1) {298    // app.get(setting)299    return this.settings[setting];300  }301302  // set value303  this.settings[setting] = val;304305  // trigger matched settings306  switch (setting) {307    case 'etag':308      debug('compile etag %s', val);309      this.set('etag fn', compileETag(val));310      break;311    case 'query parser':312      debug('compile query parser %s', val);313      this.set('query parser fn', compileQueryParser(val));314      break;315    case 'trust proxy':316      debug('compile trust proxy %s', val);317      this.set('trust proxy fn', compileTrust(val));318      break;319  }320321  return this;322};323324/**325 * Return the app's absolute pathname326 * based on the parent(s) that have327 * mounted it.328 *329 * For example if the application was330 * mounted as "/admin", which itself331 * was mounted as "/blog" then the332 * return value would be "/blog/admin".333 *334 * @return {String}335 * @api private336 */337338app.path = function(){339  return this.parent340    ? this.parent.path() + this.mountpath341    : '';342};343344/**345 * Check if `setting` is enabled (truthy).346 *347 *    app.enabled('foo')348 *    // => false349 *350 *    app.enable('foo')351 *    app.enabled('foo')352 *    // => true353 *354 * @param {String} setting355 * @return {Boolean}356 * @api public357 */358359app.enabled = function(setting){360  return !!this.set(setting);361};362363/**364 * Check if `setting` is disabled.365 *366 *    app.disabled('foo')367 *    // => true368 *369 *    app.enable('foo')370 *    app.disabled('foo')371 *    // => false372 *373 * @param {String} setting374 * @return {Boolean}375 * @api public376 */377378app.disabled = function(setting){379  return !this.set(setting);380};381382/**383 * Enable `setting`.384 *385 * @param {String} setting386 * @return {app} for chaining387 * @api public388 */389390app.enable = function(setting){391  return this.set(setting, true);392};393394/**395 * Disable `setting`.396 *397 * @param {String} setting398 * @return {app} for chaining399 * @api public400 */401402app.disable = function(setting){403  return this.set(setting, false);404};405406/**407 * Delegate `.VERB(...)` calls to `router.VERB(...)`.408 */409410methods.forEach(function(method){411  app[method] = function(path){412    if ('get' == method && 1 == arguments.length) return this.set(path);413414    this.lazyrouter();415416    var route = this._router.route(path);417    route[method].apply(route, [].slice.call(arguments, 1));418    return this;419  };420});421422/**423 * Special-cased "all" method, applying the given route `path`,424 * middleware, and callback to _every_ HTTP method.425 *426 * @param {String} path427 * @param {Function} ...428 * @return {app} for chaining429 * @api public430 */431432app.all = function(path){433  this.lazyrouter();434435  var route = this._router.route(path);436  var args = [].slice.call(arguments, 1);437  methods.forEach(function(method){438    route[method].apply(route, args);439  });440441  return this;442};443444// del -> delete alias445446app.del = deprecate.function(app.delete, 'app.del: Use app.delete instead');447448/**449 * Render the given view `name` name with `options`450 * and a callback accepting an error and the451 * rendered template string.452 *453 * Example:454 *455 *    app.render('email', { name: 'Tobi' }, function(err, html){456 *      // ...457 *    })458 *459 * @param {String} name460 * @param {String|Function} options or fn461 * @param {Function} fn462 * @api public463 */464465app.render = function(name, options, fn){466  var opts = {};467  var cache = this.cache;468  var engines = this.engines;469  var view;470471  // support callback function as second arg472  if ('function' == typeof options) {473    fn = options, options = {};474  }475476  // merge app.locals477  mixin(opts, this.locals);478479  // merge options._locals480  if (options._locals) mixin(opts, options._locals);481482  // merge options483  mixin(opts, options);484485  // set .cache unless explicitly provided486  opts.cache = null == opts.cache487    ? this.enabled('view cache')488    : opts.cache;489490  // primed cache491  if (opts.cache) view = cache[name];492493  // view494  if (!view) {495    view = new (this.get('view'))(name, {496      defaultEngine: this.get('view engine'),497      root: this.get('views'),498      engines: engines499    });500501    if (!view.path) {502      var err = new Error('Failed to lookup view "' + name + '" in views directory "' + view.root + '"');503      err.view = view;504      return fn(err);505    }506507    // prime the cache508    if (opts.cache) cache[name] = view;509  }510511  // render512  try {513    view.render(opts, fn);514  } catch (err) {515    fn(err);516  }517};518519/**520 * Listen for connections.521 *522 * A node `http.Server` is returned, with this523 * application (which is a `Function`) as its524 * callback. If you wish to create both an HTTP525 * and HTTPS server you may do so with the "http"526 * and "https" modules as shown here:527 *528 *    var http = require('http')529 *      , https = require('https')530 *      , express = require('express')531 *      , app = express();532 *533 *    http.createServer(app).listen(80);534 *    https.createServer({ ... }, app).listen(443);535 *536 * @return {http.Server}537 * @api public538 */539540app.listen = function(){541  var server = http.createServer(this);542  return server.listen.apply(server, arguments);543};544545/**546* Log error using console.error.547*548* @param {Error} err549* @api public550*/551552function logerror(err){553  if (this.get('env') !== 'test') console.error(err.stack || err.toString());554}