Skip to content
Myr

application.js

This file

Path

lib/application.js

530 lines · 11.7 KiB · JavaScript

Last changed by

Merge pull request #1503 from shesek/settings-inheritanceTJ Holowaychukbefore adoption82731da

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  , path = require('path')14  , http = require('http')15  , join = path.join;1617/**18 * Application prototype.19 */2021var app = exports = module.exports = {};2223/**24 * Initialize the server.25 *26 *   - setup default configuration27 *   - setup default middleware28 *   - setup route reflection methods29 *30 * @api private31 */3233app.init = function(){34  this.cache = {};35  this.settings = {};36  this.engines = {};37  this.defaultConfiguration();38};3940/**41 * Initialize application configuration.42 *43 * @api private44 */4546app.defaultConfiguration = function(){47  // default settings48  this.enable('x-powered-by');49  this.set('env', process.env.NODE_ENV || 'development');50  this.set('subdomain offset', 2);51  debug('booting in %s mode', this.get('env'));5253  // implicit middleware54  this.use(connect.query());55  this.use(middleware.init(this));5657  // inherit protos58  this.on('mount', function(parent){59    this.request.__proto__ = parent.request;60    this.response.__proto__ = parent.response;61    this.engines.__proto__ = parent.engines;62    this.settings.__proto__ = parent.settings;63  });6465  // router66  this._router = new Router(this);67  this.routes = this._router.map;68  this.__defineGetter__('router', function(){69    this._usedRouter = true;70    this._router.caseSensitive = this.enabled('case sensitive routing');71    this._router.strict = this.enabled('strict routing');72    return this._router.middleware;73  });7475  // setup locals76  this.locals = locals(this);7778  // default locals79  this.locals.settings = this.settings;8081  // default configuration82  this.set('views', process.cwd() + '/views');83  this.set('jsonp callback name', 'callback');8485  this.configure('development', function(){86    this.set('json spaces', 2);87  });8889  this.configure('production', function(){90    this.enable('view cache');91  });92};9394/**95 * Proxy `connect#use()` to apply settings to96 * mounted applications.97 *98 * @param {String|Function|Server} route99 * @param {Function|Server} fn100 * @return {app} for chaining101 * @api public102 */103104app.use = function(route, fn){105  var app;106107  // default route to '/'108  if ('string' != typeof route) fn = route, route = '/';109110  // express app111  if (fn.handle && fn.set) app = fn;112113  // restore .app property on req and res114  if (app) {115    app.route = route;116    fn = function(req, res, next) {117      var orig = req.app;118      app.handle(req, res, function(err){119        req.app = res.app = orig;120        req.__proto__ = orig.request;121        res.__proto__ = orig.response;122        next(err);123      });124    };125  }126127  connect.proto.use.call(this, route, fn);128129  // mounted an app130  if (app) {131    app.parent = this;132    app.emit('mount', this);133  }134135  return this;136};137138/**139 * Register the given template engine callback `fn`140 * as `ext`.141 *142 * By default will `require()` the engine based on the143 * file extension. For example if you try to render144 * a "foo.jade" file Express will invoke the following internally:145 *146 *     app.engine('jade', require('jade').__express);147 *148 * For engines that do not provide `.__express` out of the box,149 * or if you wish to "map" a different extension to the template engine150 * you may use this method. For example mapping the EJS template engine to151 * ".html" files:152 *153 *     app.engine('html', require('ejs').renderFile);154 *155 * In this case EJS provides a `.renderFile()` method with156 * the same signature that Express expects: `(path, options, callback)`,157 * though note that it aliases this method as `ejs.__express` internally158 * so if you're using ".ejs" extensions you dont need to do anything.159 *160 * Some template engines do not follow this convention, the161 * [Consolidate.js](https://github.com/visionmedia/consolidate.js)162 * library was created to map all of node's popular template163 * engines to follow this convention, thus allowing them to164 * work seamlessly within Express.165 *166 * @param {String} ext167 * @param {Function} fn168 * @return {app} for chaining169 * @api public170 */171172app.engine = function(ext, fn){173  if ('function' != typeof fn) throw new Error('callback function required');174  if ('.' != ext[0]) ext = '.' + ext;175  this.engines[ext] = fn;176  return this;177};178179/**180 * Map the given param placeholder `name`(s) to the given callback(s).181 *182 * Parameter mapping is used to provide pre-conditions to routes183 * which use normalized placeholders. For example a _:user_id_ parameter184 * could automatically load a user's information from the database without185 * any additional code,186 *187 * The callback uses the samesignature as middleware, the only differencing188 * being that the value of the placeholder is passed, in this case the _id_189 * of the user. Once the `next()` function is invoked, just like middleware190 * it will continue on to execute the route, or subsequent parameter functions.191 *192 *      app.param('user_id', function(req, res, next, id){193 *        User.find(id, function(err, user){194 *          if (err) {195 *            next(err);196 *          } else if (user) {197 *            req.user = user;198 *            next();199 *          } else {200 *            next(new Error('failed to load user'));201 *          }202 *        });203 *      });204 *205 * @param {String|Array} name206 * @param {Function} fn207 * @return {app} for chaining208 * @api public209 */210211app.param = function(name, fn){212  var self = this213    , fns = [].slice.call(arguments, 1);214215  // array216  if (Array.isArray(name)) {217    name.forEach(function(name){218      fns.forEach(function(fn){219        self.param(name, fn);220      });221    });222  // param logic223  } else if ('function' == typeof name) {224    this._router.param(name);225  // single226  } else {227    if (':' == name[0]) name = name.substr(1);228    fns.forEach(function(fn){229      self._router.param(name, fn);230    });231  }232233  return this;234};235236/**237 * Assign `setting` to `val`, or return `setting`'s value.238 *239 *    app.set('foo', 'bar');240 *    app.get('foo');241 *    // => "bar"242 *243 * Mounted servers inherit their parent server's settings.244 *245 * @param {String} setting246 * @param {String} val247 * @return {Server} for chaining248 * @api public249 */250251app.set = function(setting, val){252  if (1 == arguments.length) {253    return this.settings[setting];254  } else {255    this.settings[setting] = val;256    return this;257  }258};259260/**261 * Return the app's absolute pathname262 * based on the parent(s) that have263 * mounted it.264 *265 * For example if the application was266 * mounted as "/admin", which itself267 * was mounted as "/blog" then the268 * return value would be "/blog/admin".269 *270 * @return {String}271 * @api private272 */273274app.path = function(){275  return this.parent276    ? this.parent.path() + this.route277    : '';278};279280/**281 * Check if `setting` is enabled (truthy).282 *283 *    app.enabled('foo')284 *    // => false285 *286 *    app.enable('foo')287 *    app.enabled('foo')288 *    // => true289 *290 * @param {String} setting291 * @return {Boolean}292 * @api public293 */294295app.enabled = function(setting){296  return !!this.set(setting);297};298299/**300 * Check if `setting` is disabled.301 *302 *    app.disabled('foo')303 *    // => true304 *305 *    app.enable('foo')306 *    app.disabled('foo')307 *    // => false308 *309 * @param {String} setting310 * @return {Boolean}311 * @api public312 */313314app.disabled = function(setting){315  return !this.set(setting);316};317318/**319 * Enable `setting`.320 *321 * @param {String} setting322 * @return {app} for chaining323 * @api public324 */325326app.enable = function(setting){327  return this.set(setting, true);328};329330/**331 * Disable `setting`.332 *333 * @param {String} setting334 * @return {app} for chaining335 * @api public336 */337338app.disable = function(setting){339  return this.set(setting, false);340};341342/**343 * Configure callback for zero or more envs,344 * when no `env` is specified that callback will345 * be invoked for all environments. Any combination346 * can be used multiple times, in any order desired.347 *348 * Examples:349 *350 *    app.configure(function(){351 *      // executed for all envs352 *    });353 *354 *    app.configure('stage', function(){355 *      // executed staging env356 *    });357 *358 *    app.configure('stage', 'production', function(){359 *      // executed for stage and production360 *    });361 *362 * Note:363 *364 *  These callbacks are invoked immediately, and365 *  are effectively sugar for the following:366 *367 *     var env = process.env.NODE_ENV || 'development';368 *369 *      switch (env) {370 *        case 'development':371 *          ...372 *          break;373 *        case 'stage':374 *          ...375 *          break;376 *        case 'production':377 *          ...378 *          break;379 *      }380 *381 * @param {String} env...382 * @param {Function} fn383 * @return {app} for chaining384 * @api public385 */386387app.configure = function(env, fn){388  var envs = 'all'389    , args = [].slice.call(arguments);390  fn = args.pop();391  if (args.length) envs = args;392  if ('all' == envs || ~envs.indexOf(this.settings.env)) fn.call(this);393  return this;394};395396/**397 * Delegate `.VERB(...)` calls to `router.VERB(...)`.398 */399400methods.forEach(function(method){401  app[method] = function(path){402    if ('get' == method && 1 == arguments.length) return this.set(path);403404    // if no router attached yet, attach the router405    if (!this._usedRouter) this.use(this.router);406407    // setup route408    this._router[method].apply(this._router, arguments);409    return this;410  };411});412413/**414 * Special-cased "all" method, applying the given route `path`,415 * middleware, and callback to _every_ HTTP method.416 *417 * @param {String} path418 * @param {Function} ...419 * @return {app} for chaining420 * @api public421 */422423app.all = function(path){424  var args = arguments;425  methods.forEach(function(method){426    app[method].apply(this, args);427  }, this);428  return this;429};430431// del -> delete alias432433app.del = app.delete;434435/**436 * Render the given view `name` name with `options`437 * and a callback accepting an error and the438 * rendered template string.439 *440 * Example:441 *442 *    app.render('email', { name: 'Tobi' }, function(err, html){443 *      // ...444 *    })445 *446 * @param {String} name447 * @param {String|Function} options or fn448 * @param {Function} fn449 * @api public450 */451452app.render = function(name, options, fn){453  var opts = {}454    , cache = this.cache455    , engines = this.engines456    , view;457458  // support callback function as second arg459  if ('function' == typeof options) {460    fn = options, options = {};461  }462463  // merge app.locals464  utils.merge(opts, this.locals);465466  // merge options._locals467  if (options._locals) utils.merge(opts, options._locals);468469  // merge options470  utils.merge(opts, options);471472  // set .cache unless explicitly provided473  opts.cache = null == opts.cache474    ? this.enabled('view cache')475    : opts.cache;476477  // primed cache478  if (opts.cache) view = cache[name];479480  // view481  if (!view) {482    view = new View(name, {483      defaultEngine: this.get('view engine'),484      root: this.get('views'),485      engines: engines486    });487488    if (!view.path) {489      var err = new Error('Failed to lookup view "' + name + '"');490      err.view = view;491      return fn(err);492    }493494    // prime the cache495    if (opts.cache) cache[name] = view;496  }497498  // render499  try {500    view.render(opts, fn);501  } catch (err) {502    fn(err);503  }504};505506/**507 * Listen for connections.508 *509 * A node `http.Server` is returned, with this510 * application (which is a `Function`) as its511 * callback. If you wish to create both an HTTP512 * and HTTPS server you may do so with the "http"513 * and "https" modules as shown here:514 *515 *    var http = require('http')516 *      , https = require('https')517 *      , express = require('express')518 *      , app = express();519 *520 *    http.createServer(app).listen(80);521 *    https.createServer({ ... }, app).listen(443);522 *523 * @return {http.Server}524 * @api public525 */526527app.listen = function(){528  var server = http.createServer(this);529  return server.listen.apply(server, arguments);530};