Skip to content
Myr

application.js

This file

Path

lib/application.js

476 lines · 10.6 KiB · JavaScript

Last changed by

Merge pull request #1899 from visionmedia/remove-configureRoman Shtylmanbefore adoptionac2cbef

History of this file

Take it

1/**2 * Module dependencies.3 */45var connect = require('connect')6  , Router = require('./router')7  , methods = require('methods')8  , middleware = require('./middleware')9  , debug = require('debug')('express:application')10  , locals = require('./utils').locals11  , View = require('./view')12  , utils = connect.utils13  , http = require('http');1415/**16 * Application prototype.17 */1819var app = exports = module.exports = {};2021/**22 * Initialize the server.23 *24 *   - setup default configuration25 *   - setup default middleware26 *   - setup route reflection methods27 *28 * @api private29 */3031app.init = function(){32  this.cache = {};33  this.settings = {};34  this.engines = {};35  this.defaultConfiguration();36};3738/**39 * Initialize application configuration.40 *41 * @api private42 */4344app.defaultConfiguration = function(){45  // default settings46  this.enable('x-powered-by');47  this.enable('etag');48  this.set('env', process.env.NODE_ENV || 'development');49  this.set('subdomain offset', 2);50  debug('booting in %s mode', this.get('env'));5152  // implicit middleware53  this.use(connect.query());54  this.use(middleware.init(this));5556  // inherit protos57  this.on('mount', function(parent){58    this.request.__proto__ = parent.request;59    this.response.__proto__ = parent.response;60    this.engines.__proto__ = parent.engines;61    this.settings.__proto__ = parent.settings;62  });6364  // router65  this._router = new Router(this);66  this.routes = this._router.map;67  this.__defineGetter__('router', function(){68    this._usedRouter = true;69    this._router.caseSensitive = this.enabled('case sensitive routing');70    this._router.strict = this.enabled('strict routing');71    return this._router.middleware;72  });7374  // setup locals75  this.locals = locals(this);7677  // default locals78  this.locals.settings = this.settings;7980  // default configuration81  this.set('view', View);82  this.set('views', process.cwd() + '/views');83  this.set('jsonp callback name', 'callback');8485  if (this.get('env') === 'production') {86    this.enable('view cache');87  };88};8990/**91 * Proxy `connect#use()` to apply settings to92 * mounted applications.93 *94 * @param {String|Function|Server} route95 * @param {Function|Server} fn96 * @return {app} for chaining97 * @api public98 */99100app.use = function(route, fn){101  var app;102103  // default route to '/'104  if ('string' != typeof route) fn = route, route = '/';105106  // express app107  if (fn.handle && fn.set) app = fn;108109  // restore .app property on req and res110  if (app) {111    app.route = route;112    fn = function(req, res, next) {113      var orig = req.app;114      app.handle(req, res, function(err){115        req.__proto__ = orig.request;116        res.__proto__ = orig.response;117        next(err);118      });119    };120  }121122  connect.proto.use.call(this, route, fn);123124  // mounted an app125  if (app) {126    app.parent = this;127    app.emit('mount', this);128  }129130  return this;131};132133/**134 * Register the given template engine callback `fn`135 * as `ext`.136 *137 * By default will `require()` the engine based on the138 * file extension. For example if you try to render139 * a "foo.jade" file Express will invoke the following internally:140 *141 *     app.engine('jade', require('jade').__express);142 *143 * For engines that do not provide `.__express` out of the box,144 * or if you wish to "map" a different extension to the template engine145 * you may use this method. For example mapping the EJS template engine to146 * ".html" files:147 *148 *     app.engine('html', require('ejs').renderFile);149 *150 * In this case EJS provides a `.renderFile()` method with151 * the same signature that Express expects: `(path, options, callback)`,152 * though note that it aliases this method as `ejs.__express` internally153 * so if you're using ".ejs" extensions you dont need to do anything.154 *155 * Some template engines do not follow this convention, the156 * [Consolidate.js](https://github.com/visionmedia/consolidate.js)157 * library was created to map all of node's popular template158 * engines to follow this convention, thus allowing them to159 * work seamlessly within Express.160 *161 * @param {String} ext162 * @param {Function} fn163 * @return {app} for chaining164 * @api public165 */166167app.engine = function(ext, fn){168  if ('function' != typeof fn) throw new Error('callback function required');169  if ('.' != ext[0]) ext = '.' + ext;170  this.engines[ext] = fn;171  return this;172};173174/**175 * Map the given param placeholder `name`(s) to the given callback(s).176 *177 * Parameter mapping is used to provide pre-conditions to routes178 * which use normalized placeholders. For example a _:user_id_ parameter179 * could automatically load a user's information from the database without180 * any additional code,181 *182 * The callback uses the same signature as middleware, the only difference183 * being that the value of the placeholder is passed, in this case the _id_184 * of the user. Once the `next()` function is invoked, just like middleware185 * it will continue on to execute the route, or subsequent parameter functions.186 *187 *      app.param('user_id', function(req, res, next, id){188 *        User.find(id, function(err, user){189 *          if (err) {190 *            next(err);191 *          } else if (user) {192 *            req.user = user;193 *            next();194 *          } else {195 *            next(new Error('failed to load user'));196 *          }197 *        });198 *      });199 *200 * @param {String|Array} name201 * @param {Function} fn202 * @return {app} for chaining203 * @api public204 */205206app.param = function(name, fn){207  var self = this208    , fns = [].slice.call(arguments, 1);209210  // array211  if (Array.isArray(name)) {212    name.forEach(function(name){213      fns.forEach(function(fn){214        self.param(name, fn);215      });216    });217  // param logic218  } else if ('function' == typeof name) {219    this._router.param(name);220  // single221  } else {222    if (':' == name[0]) name = name.substr(1);223    fns.forEach(function(fn){224      self._router.param(name, fn);225    });226  }227228  return this;229};230231/**232 * Assign `setting` to `val`, or return `setting`'s value.233 *234 *    app.set('foo', 'bar');235 *    app.get('foo');236 *    // => "bar"237 *238 * Mounted servers inherit their parent server's settings.239 *240 * @param {String} setting241 * @param {*} [val]242 * @return {Server} for chaining243 * @api public244 */245246app.set = function(setting, val){247  if (1 == arguments.length) {248    return this.settings[setting];249  } else {250    this.settings[setting] = val;251    return this;252  }253};254255/**256 * Return the app's absolute pathname257 * based on the parent(s) that have258 * mounted it.259 *260 * For example if the application was261 * mounted as "/admin", which itself262 * was mounted as "/blog" then the263 * return value would be "/blog/admin".264 *265 * @return {String}266 * @api private267 */268269app.path = function(){270  return this.parent271    ? this.parent.path() + this.route272    : '';273};274275/**276 * Check if `setting` is enabled (truthy).277 *278 *    app.enabled('foo')279 *    // => false280 *281 *    app.enable('foo')282 *    app.enabled('foo')283 *    // => true284 *285 * @param {String} setting286 * @return {Boolean}287 * @api public288 */289290app.enabled = function(setting){291  return !!this.set(setting);292};293294/**295 * Check if `setting` is disabled.296 *297 *    app.disabled('foo')298 *    // => true299 *300 *    app.enable('foo')301 *    app.disabled('foo')302 *    // => false303 *304 * @param {String} setting305 * @return {Boolean}306 * @api public307 */308309app.disabled = function(setting){310  return !this.set(setting);311};312313/**314 * Enable `setting`.315 *316 * @param {String} setting317 * @return {app} for chaining318 * @api public319 */320321app.enable = function(setting){322  return this.set(setting, true);323};324325/**326 * Disable `setting`.327 *328 * @param {String} setting329 * @return {app} for chaining330 * @api public331 */332333app.disable = function(setting){334  return this.set(setting, false);335};336337/**338 * Delegate `.VERB(...)` calls to `router.VERB(...)`.339 */340341methods.forEach(function(method){342  app[method] = function(path){343    if ('get' == method && 1 == arguments.length) return this.set(path);344345    // deprecated346    if (Array.isArray(path)) {347      console.trace('passing an array to app.VERB() is deprecated and will be removed in 4.0');348    }349350    // if no router attached yet, attach the router351    if (!this._usedRouter) this.use(this.router);352353    // setup route354    this._router[method].apply(this._router, arguments);355    return this;356  };357});358359/**360 * Special-cased "all" method, applying the given route `path`,361 * middleware, and callback to _every_ HTTP method.362 *363 * @param {String} path364 * @param {Function} ...365 * @return {app} for chaining366 * @api public367 */368369app.all = function(path){370  var args = arguments;371  methods.forEach(function(method){372    app[method].apply(this, args);373  }, this);374  return this;375};376377// del -> delete alias378379app.del = app.delete;380381/**382 * Render the given view `name` name with `options`383 * and a callback accepting an error and the384 * rendered template string.385 *386 * Example:387 *388 *    app.render('email', { name: 'Tobi' }, function(err, html){389 *      // ...390 *    })391 *392 * @param {String} name393 * @param {String|Function} options or fn394 * @param {Function} fn395 * @api public396 */397398app.render = function(name, options, fn){399  var opts = {}400    , cache = this.cache401    , engines = this.engines402    , view;403404  // support callback function as second arg405  if ('function' == typeof options) {406    fn = options, options = {};407  }408409  // merge app.locals410  utils.merge(opts, this.locals);411412  // merge options._locals413  if (options._locals) utils.merge(opts, options._locals);414415  // merge options416  utils.merge(opts, options);417418  // set .cache unless explicitly provided419  opts.cache = null == opts.cache420    ? this.enabled('view cache')421    : opts.cache;422423  // primed cache424  if (opts.cache) view = cache[name];425426  // view427  if (!view) {428    view = new (this.get('view'))(name, {429      defaultEngine: this.get('view engine'),430      root: this.get('views'),431      engines: engines432    });433434    if (!view.path) {435      var err = new Error('Failed to lookup view "' + name + '" in views directory "' + view.root + '"');436      err.view = view;437      return fn(err);438    }439440    // prime the cache441    if (opts.cache) cache[name] = view;442  }443444  // render445  try {446    view.render(opts, fn);447  } catch (err) {448    fn(err);449  }450};451452/**453 * Listen for connections.454 *455 * A node `http.Server` is returned, with this456 * application (which is a `Function`) as its457 * callback. If you wish to create both an HTTP458 * and HTTPS server you may do so with the "http"459 * and "https" modules as shown here:460 *461 *    var http = require('http')462 *      , https = require('https')463 *      , express = require('express')464 *      , app = express();465 *466 *    http.createServer(app).listen(80);467 *    https.createServer({ ... }, app).listen(443);468 *469 * @return {http.Server}470 * @api public471 */472473app.listen = function(){474  var server = http.createServer(this);475  return server.listen.apply(server, arguments);476};