Skip to content
Myr

application.js

This file

Path

lib/application.js

555 lines · 12.3 KiB · JavaScript

Last changed by

Fixed req/res proto inheritanceTJ Holowaychukbefore adoption441b309

History of this file

Take it

12/*!3 * Express - application4 * Copyright(c) 2010-2012 TJ Holowaychuk <tj@vision-media.ca>5 * MIT Licensed6 */78/**9 * Module dependencies.10 */1112var connect = require('connect')13  , Router = require('./router')14  , methods = Router.methods.concat('del', 'all')15  , middleware = require('./middleware')16  , debug = require('debug')('express:application')17  , View = require('./view')18  , url = require('url')19  , utils = connect.utils20  , path = require('path')21  , http = require('http')22  , join = path.join23  , fs = require('fs');2425/**26 * Application prototype.27 */2829var app = exports = module.exports = {};3031/**32 * Initialize the server.33 *34 *   - setup default configuration35 *   - setup default middleware36 *   - setup route reflection methods37 *38 * @api private39 */4041app.init = function(){42  var self = this;43  this.cache = {};44  this.settings = {};45  this.engines = {};46  this.viewCallbacks = [];47  this.defaultConfiguration();48};4950/**51 * Initialize application configuration.52 *53 * @api private54 */5556app.defaultConfiguration = function(){57  var self = this;5859  // default settings60  this.set('env', process.env.NODE_ENV || 'development');61  debug('booting in %s mode', this.get('env'));6263  // implicit middleware64  this.use(connect.query());65  this.use(middleware.init(this));6667  // app locals68  this.locals = function(obj){69    for (var key in obj) self.locals[key] = obj[key];70    return self;71  };7273  // response locals74  this.locals.use = function(fn){75    if (3 == fn.length) {76      self.viewCallbacks.push(fn);77    } else {78      self.viewCallbacks.push(function(req, res, done){79        fn(req, res);80        done();81      });82    }83    return this;84  };8586  // inherit view callbacks87  this.on('mount', function(parent){88    this.request.__proto__ = parent.request;89    this.response.__proto__ = parent.response;90    this.engines.__proto__ = parent.engines;91    this.viewCallbacks = parent.viewCallbacks.slice(0);92  });9394  // router95  this._router = new Router(this);96  this.routes = this._router.routes;97  this.__defineGetter__('router', function(){98    this._usedRouter = true;99    this._router.caseSensitive = this.enabled('case sensitive routing');100    this._router.strict = this.enabled('strict routing');101    return this._router.middleware;102  });103104  // default locals105  this.locals.settings = this.settings;106107  // default configuration108  this.enable('jsonp callback');109110  this.configure('development', function(){111    this.set('json spaces', 2);112  });113114  this.configure('production', function(){115    this.enable('view cache');116  });117};118119/**120 * Proxy `connect#use()` to apply settings to121 * mounted applications.122 *123 * @param {String|Function|Server} route124 * @param {Function|Server} fn125 * @return {app} for chaining126 * @api public127 */128129app.use = function(route, fn){130  var app, home, handle;131132  // default route to '/'133  if ('string' != typeof route) fn = route, route = '/';134135  // express app136  if (fn.handle && fn.set) app = fn;137138  // restore .app property on req and res139  if (app) {140    app.route = route;141    fn = function(req, res, next) {142      var orig = req.app;143      app.handle(req, res, function(err){144        req.app = res.app = orig;145        req.__proto__ = orig.request;146        res.__proto__ = orig.response;147        next(err);148      });149    };150  }151152  connect.proto.use.call(this, route, fn);153154  // mounted an app155  if (app) {156    app.parent = this;157    app.emit('mount', this);158  }159160  return this;161};162163/**164 * Register the given template engine callback `fn`165 * as `ext`.166 *167 * By default will `require()` the engine based on the168 * file extension. For example if you try to render169 * a "foo.jade" file Express will invoke the following internally:170 *171 *     app.engine('jade', require('jade').__express);172 *173 * For engines that do not provide `.__express` out of the box,174 * or if you wish to "map" a different extension to the template engine175 * you may use this method. For example mapping the EJS template engine to176 * ".html" files:177 *178 *     app.engine('html', require('ejs').renderFile);179 *180 * In this case EJS provides a `.renderFile()` method with181 * the same signature that Express expects: `(path, options, callback)`,182 * though note that it aliases this method as `ejs.__express` internally183 * so if you're using ".ejs" extensions you dont need to do anything.184 *185 * Some template engines do not follow this convention, the186 * [Consolidate.js](https://github.com/visionmedia/consolidate.js)187 * library was created to map all of node's popular template188 * engines to follow this convention, thus allowing them to189 * work seemlessly within Express.190 *191 * @param {String} ext192 * @param {Function} fn193 * @return {app} for chaining194 * @api public195 */196197app.engine = function(ext, fn){198  if ('function' != typeof fn) throw new Error('callback function required');199  if ('.' != ext[0]) ext = '.' + ext;200  this.engines[ext] = fn;201  return this;202};203204/**205 * Map the given param placeholder `name`(s) to the given callback(s).206 *207 * Parameter mapping is used to provide pre-conditions to routes208 * which use normalized placeholders. For example a _:user_id_ parameter209 * could automatically load a user's information from the database without210 * any additional code,211 *212 * The callback uses the samesignature as middleware, the only differencing213 * being that the value of the placeholder is passed, in this case the _id_214 * of the user. Once the `next()` function is invoked, just like middleware215 * it will continue on to execute the route, or subsequent parameter functions.216 *217 *      app.param('user_id', function(req, res, next, id){218 *        User.find(id, function(err, user){219 *          if (err) {220 *            next(err);221 *          } else if (user) {222 *            req.user = user;223 *            next();224 *          } else {225 *            next(new Error('failed to load user'));226 *          }227 *        });228 *      });229 *230 * @param {String|Array} name231 * @param {Function} fn232 * @return {app} for chaining233 * @api public234 */235236app.param = function(name, fn){237  var self = this238    , fns = [].slice.call(arguments, 1);239240  // array241  if (Array.isArray(name)) {242    name.forEach(function(name){243      fns.forEach(function(fn){244        self.param(name, fn);245      });246    });247  // param logic248  } else if ('function' == typeof name) {249    this._router.param(name);250  // single251  } else {252    if (':' == name[0]) name = name.substr(1);253    fns.forEach(function(fn){254      self._router.param(name, fn);255    });256  }257258  return this;259};260261/**262 * Assign `setting` to `val`, or return `setting`'s value.263 *264 *    app.set('foo', 'bar');265 *    app.get('foo');266 *    // => "bar"267 *268 * Mounted servers inherit their parent server's settings.269 *270 * @param {String} setting271 * @param {String} val272 * @return {Server} for chaining273 * @api public274 */275276app.set = function(setting, val){277  if (1 == arguments.length) {278    if (this.settings.hasOwnProperty(setting)) {279      return this.settings[setting];280    } else if (this.parent) {281      return this.parent.set(setting);282    }283  } else {284    this.settings[setting] = val;285    return this;286  }287};288289/**290 * Return the app's absolute pathname291 * based on the parent(s) that have292 * mounted it.293 *294 * For example if the application was295 * mounted as "/admin", which itself296 * was mounted as "/blog" then the297 * return value would be "/blog/admin".298 *299 * @return {String}300 * @api private301 */302303app.path = function(){304  return this.parent305    ? this.parent.path() + this.route306    : '';307};308309/**310 * Check if `setting` is enabled (truthy).311 *312 *    app.enabled('foo')313 *    // => false314 *315 *    app.enable('foo')316 *    app.enabled('foo')317 *    // => true318 *319 * @param {String} setting320 * @return {Boolean}321 * @api public322 */323324app.enabled = function(setting){325  return !!this.set(setting);326};327328/**329 * Check if `setting` is disabled.330 *331 *    app.disabled('foo')332 *    // => true333 *334 *    app.enable('foo')335 *    app.disabled('foo')336 *    // => false337 *338 * @param {String} setting339 * @return {Boolean}340 * @api public341 */342343app.disabled = function(setting){344  return !this.set(setting);345};346347/**348 * Enable `setting`.349 *350 * @param {String} setting351 * @return {app} for chaining352 * @api public353 */354355app.enable = function(setting){356  return this.set(setting, true);357};358359/**360 * Disable `setting`.361 *362 * @param {String} setting363 * @return {app} for chaining364 * @api public365 */366367app.disable = function(setting){368  return this.set(setting, false);369};370371/**372 * Configure callback for zero or more envs,373 * when no `env` is specified that callback will374 * be invoked for all environments. Any combination375 * can be used multiple times, in any order desired.376 *377 * Examples:378 *379 *    app.configure(function(){380 *      // executed for all envs381 *    });382 *383 *    app.configure('stage', function(){384 *      // executed staging env385 *    });386 *387 *    app.configure('stage', 'production', function(){388 *      // executed for stage and production389 *    });390 *391 * Note:392 *393 *  These callbacks are invoked immediately, and394 *  are effectively sugar for the following:395 *396 *     var env = process.env.NODE_ENV || 'development';397 *398 *      switch (env) {399 *        case 'development':400 *          ...401 *          break;402 *        case 'stage':403 *          ...404 *          break;405 *        case 'production':406 *          ...407 *          break;408 *      }409 *410 * @param {String} env...411 * @param {Function} fn412 * @return {app} for chaining413 * @api public414 */415416app.configure = function(env, fn){417  var envs = 'all'418    , args = [].slice.call(arguments);419  fn = args.pop();420  if (args.length) envs = args;421  if ('all' == envs || ~envs.indexOf(this.settings.env)) fn.call(this);422  return this;423};424425/**426 * Delegate `.VERB(...)` calls to `.route(VERB, ...)`.427 */428429methods.forEach(function(method){430  app[method] = function(path){431    if ('get' == method && 1 == arguments.length) return this.set(path); 432    var args = [method].concat([].slice.call(arguments));433    if (!this._usedRouter) this.use(this.router);434    return this._router.route.apply(this._router, args);435  }436});437438/**439 * Special-cased "all" method, applying the given route `path`,440 * middleware, and callback to _every_ HTTP method.441 *442 * @param {String} path443 * @param {Function} ...444 * @return {app} for chaining445 * @api public446 */447448app.all = function(path){449  var args = arguments;450  methods.forEach(function(method){451    if ('all' == method || 'del' == method) return;452    app[method].apply(this, args);453  }, this);454  return this;455};456457// del -> delete alias458459app.del = app.delete;460461/**462 * Render the given view `name` name with `options`463 * and a callback accepting an error and the464 * rendered template string.465 *466 * Example:467 *468 *    app.render('email', { name: 'Tobi' }, function(err, html){469 *      // ...470 *    })471 *472 * @param {String} name473 * @param {String|Function} options or fn474 * @param {Function} fn475 * @api public476 */477478app.render = function(name, options, fn){479  var self = this480    , opts = {}481    , cache = this.cache482    , engines = this.engines483    , view;484485  // support callback function as second arg486  if ('function' == typeof options) {487    fn = options, options = {};488  }489490  // merge app.locals491  utils.merge(opts, this.locals);492493  // merge options.locals494  if (options.locals) utils.merge(opts, options.locals);495496  // merge options497  utils.merge(opts, options);498499  // set .cache unless explicitly provided500  opts.cache = null == opts.cache501    ? this.enabled('view cache')502    : opts.cache;503504  // primed cache505  if (opts.cache) view = cache[name];506507  // view508  if (!view) {509    view = new View(name, {510        defaultEngine: this.get('view engine')511      , root: this.get('views') || process.cwd() + '/views'512      , engines: engines513    });514515    if (!view.path) {516      return fn(new Error('Failed to lookup view "' + name + '"'));517    }518519    // prime the cache520    if (opts.cache) cache[name] = view;521  }522523  // render524  try {525    view.render(opts, fn);526  } catch (err) {527    fn(err);528  }529};530531/**532 * Listen for connections.533 *534 * A node `http.Server` is returned, with this535 * application (which is a `Function`) as its536 * callback. If you wish to create both an HTTP537 * and HTTPS server you may do so with the "http"538 * and "https" modules as shown here:539 *540 *    var http = require('http')541 *      , https = require('https')542 *      , express = require('express')543 *      , app = express();544 *545 *    http.createServer(app).listen(80);546 *    http.createServer({ ... }, app).listen(443);547 *548 * @return {http.Server}549 * @api public550 */551552app.listen = function(){553  var server = http.createServer(this);554  return server.listen.apply(server, arguments);555};