Skip to content
Myr

application.js

This file

Path

lib/application.js

532 lines · 11.3 KiB · JavaScript

Last changed by

removed debug() for .use()TJ Holowaychukbefore adoption18fa2c9

History of this file

Take it

12/*!3 * Express - proto4 * Copyright(c) 2010 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();4849  // route reflection methods50  methods.forEach(function(method){51    self.lookup[method] = function(path){52      return self._router.lookup(method, path);53    };5455    self.remove[method] = function(path){56      return self._router.lookup(method, path).remove();57    };58  });5960  // del -> delete61  self.lookup.del = self.lookup.delete;62  self.remove.del = self.remove.delete;63};6465/**66 * Initialize application configuration.67 *68 * @api private69 */7071app.defaultConfiguration = function(){72  var self = this;7374  // default settings75  this.set('env', process.env.NODE_ENV || 'development');76  debug('booting in %s mode', this.get('env'));7778  // implicit middleware79  this.use(connect.query());80  this.use(middleware.init(this));8182  // app locals83  this.locals = function(obj){84    for (var key in obj) self.locals[key] = obj[key];85    return self;86  };8788  // response locals89  this.locals.use = function(fn){90    if (3 == fn.length) {91      self.viewCallbacks.push(fn);92    } else {93      self.viewCallbacks.push(function(req, res, done){94        fn(req, res);95        done();96      });97    }98    return this;99  };100101  // router102  this._router = new Router(this);103  this.routes = this._router.routes;104  this.__defineGetter__('router', function(){105    this._usedRouter = true;106    this._router.caseSensitive = this.enabled('case sensitive routing');107    this._router.strict = this.enabled('strict routing');108    return this._router.middleware;109  });110111  // default locals112  this.locals.settings = this.settings;113114  // default configuration115  this.configure('development', function(){116    this.set('json spaces', 2);117  });118119  this.configure('production', function(){120    this.enable('view cache');121  });122};123124/**125 * Remove routes matching the given `path`.126 *127 * @param {Route} path128 * @return {Boolean}129 * @api public130 */131132app.remove = function(path){133  return this._router.lookup('all', path).remove();134};135136/**137 * Lookup routes defined with a path138 * equivalent to `path`.139 *140 * @param {String} path141 * @return {Array}142 * @api public143 */144145app.lookup = function(path){146  return this._router.lookup('all', path);147};148149/**150 * Proxy `connect#use()` to apply settings to151 * mounted applications.152 *153 * @param {String|Function|Server} route154 * @param {Function|Server} fn155 * @return {app} for chaining156 * @api public157 */158159app.use = function(route, fn){160  var app, home, handle;161162  // default route to '/'163  if ('string' != typeof route) fn = route, route = '/';164165  // express app166  if (fn.handle && fn.set) app = fn;167168  // restore .app property on req and res169  if (app) {170    app.route = route;171    fn = function(req, res, next) {172      var orig = req.app;173      app.handle(req, res, function(err){174        req.app = res.app = orig;175        next(err);176      });177    };178  }179180  connect.proto.use.call(this, route, fn);181182  // mounted an app183  if (app) {184    app.parent = this;185    app.emit('mount', this);186  }187188  return this;189};190191/**192 * Register the given template engine callback `fn`193 * as `ext`. For example we may wish to map ".html"194 * files to ejs rather than using the ".ejs" extension.195 *196 *    app.engine('.html', require('ejs').render);197 *198 * or199 *200 *    app.engine('html', require('ejs').render);201 *202 * @param {String} ext203 * @param {Function} fn204 * @return {app} for chaining205 * @api public206 */207208app.engine = function(ext, fn){209  if ('.' != ext[0]) ext = '.' + ext;210  this.engines[ext] = fn;211  return this;212};213214/**215 * Map the given param placeholder `name`(s) to the given callback(s).216 *217 * Param mapping is used to provide pre-conditions to routes218 * which us normalized placeholders. This callback has the same219 * signature as regular middleware, for example below when ":userId"220 * is used this function will be invoked in an attempt to load the user.221 *222 *      app.param('userId', function(req, res, next, id){223 *        User.find(id, function(err, user){224 *          if (err) {225 *            next(err);226 *          } else if (user) {227 *            req.user = user;228 *            next();229 *          } else {230 *            next(new Error('failed to load user'));231 *          }232 *        });233 *      });234 *235 * Passing a single function allows you to map logic236 * to the values passed to `app.param()`, for example237 * this is useful to provide coercion support in a concise manner.238 *239 * The following example maps regular expressions to param values240 * ensuring that they match, otherwise passing control to the next241 * route:242 *243 *      app.param(function(name, regexp){244 *        if (regexp instanceof RegExp) {245 *          return function(req, res, next, val){246 *            var captures;247 *            if (captures = regexp.exec(String(val))) {248 *              req.params[name] = captures;249 *              next();250 *            } else {251 *              next('route');252 *            }253 *          }254 *        }255 *      });256 *257 * We can now use it as shown below, where "/commit/:commit" expects258 * that the value for ":commit" is at 5 or more digits. The capture259 * groups are then available as `req.params.commit` as we defined260 * in the function above.261 *262 *    app.param('commit', /^\d{5,}$/);263 *264 * For more of this useful functionality take a look265 * at [express-params](http://github.com/visionmedia/express-params).266 *267 * @param {String|Array|Function} name268 * @param {Function} fn269 * @return {app} for chaining270 * @api public271 */272273app.param = function(name, fn){274  var self = this275    , fns = [].slice.call(arguments, 1);276277  // array278  if (Array.isArray(name)) {279    name.forEach(function(name){280      fns.forEach(function(fn){281        self.param(name, fn);282      });283    });284  // param logic285  } else if ('function' == typeof name) {286    this._router.param(name);287  // single288  } else {289    if (':' == name[0]) name = name.substr(1);290    fns.forEach(function(fn){291      self._router.param(name, fn);292    });293  }294295  return this;296};297298/**299 * Assign `setting` to `val`, or return `setting`'s value.300 * Mounted servers inherit their parent server's settings.301 *302 * @param {String} setting303 * @param {String} val304 * @return {Server|Mixed} for chaining, or the setting value305 * @api public306 */307308app.set = function(setting, val){309  if (1 == arguments.length) {310    if (this.settings.hasOwnProperty(setting)) {311      return this.settings[setting];312    } else if (this.parent) {313      return this.parent.set(setting);314    }315  } else {316    this.settings[setting] = val;317    return this;318  }319};320321/**322 * Return the app's absolute pathname323 * based on the parent(s) that have324 * mounted it.325 *326 * @return {String}327 * @api private328 */329330app.path = function(){331  return this.parent332    ? this.parent.path() + this.route333    : '';334};335336/**337 * Check if `setting` is enabled.338 *339 * @param {String} setting340 * @return {Boolean}341 * @api public342 */343344app.enabled = function(setting){345  return !!this.set(setting);346};347348/**349 * Check if `setting` is disabled.350 *351 * @param {String} setting352 * @return {Boolean}353 * @api public354 */355356app.disabled = function(setting){357  return !this.set(setting);358};359360/**361 * Enable `setting`.362 *363 * @param {String} setting364 * @return {app} for chaining365 * @api public366 */367368app.enable = function(setting){369  return this.set(setting, true);370};371372/**373 * Disable `setting`.374 *375 * @param {String} setting376 * @return {app} for chaining377 * @api public378 */379380app.disable = function(setting){381  return this.set(setting, false);382};383384/**385 * Configure callback for zero or more envs,386 * when no env is specified that callback will387 * be invoked for all environments. Any combination388 * can be used multiple times, in any order desired.389 *390 * Examples:391 *392 *    app.configure(function(){393 *      // executed for all envs394 *    });395 *396 *    app.configure('stage', function(){397 *      // executed staging env398 *    });399 *400 *    app.configure('stage', 'production', function(){401 *      // executed for stage and production402 *    });403 *404 * @param {String} env...405 * @param {Function} fn406 * @return {app} for chaining407 * @api public408 */409410app.configure = function(env, fn){411  var envs = 'all'412    , args = [].slice.call(arguments);413  fn = args.pop();414  if (args.length) envs = args;415  if ('all' == envs || ~envs.indexOf(this.settings.env)) fn.call(this);416  return this;417};418419/**420 * Listen for connections.421 *422 * This method takes the same arguments423 * as node's `http.Server#listen()`.  424 *425 * @return {http.Server}426 * @api public427 */428429app.listen = function(){430  var server = http.createServer(this);431  return server.listen.apply(server, arguments);432};433434/**435 * Delegate `.VERB(...)` calls to `.route(VERB, ...)`.436 */437438methods.forEach(function(method){439  app[method] = function(path){440    if ('get' == method && 1 == arguments.length) return this.set(path); 441    var args = [method].concat([].slice.call(arguments));442    if (!this._usedRouter) this.use(this.router);443    return this._router.route.apply(this._router, args);444  }445});446447/**448 * Special-cased "all" method, applying the given route `path`,449 * middleware, and callback to _every_ HTTP method.450 *451 * @param {String} path452 * @param {Function} ...453 * @return {app} for chaining454 * @api public455 */456457app.all = function(path){458  var args = arguments;459  methods.forEach(function(method){460    if ('all' == method || 'del' == method) return;461    app[method].apply(this, args);462  }, this);463  return this;464};465466// del -> delete alias467468app.del = app.delete;469470/**471 * Render the given view `name` name with `options`472 * and a callback accepting an error and the473 * rendered template string.474 *475 * @param {String} name476 * @param {String|Function} options or fn477 * @param {Function} fn478 * @api public479 */480481app.render = function(name, options, fn){482  var self = this483    , opts = {}484    , cache = this.cache485    , engines = this.engines486    , view;487488  // support callback function as second arg489  if ('function' == typeof options) {490    fn = options, options = {};491  }492493  // merge app.locals494  utils.merge(opts, this.locals);495496  // merge options.locals497  if (options.locals) utils.merge(opts, options.locals);498499  // merge options500  utils.merge(opts, options);501502  // set .cache unless explicitly provided503  opts.cache = null == opts.cache504    ? this.enabled('view cache')505    : opts.cache;506507  // primed cache508  if (opts.cache) view = cache[name];509510  // view511  if (!view) {512    view = new View(name, {513        defaultEngine: this.get('view engine')514      , root: this.get('views') || process.cwd() + '/views'515      , engines: engines516    });517518    if (!view.path) {519      return fn(new Error('Failed to lookup view "' + name + '"'));520    }521522    // prime the cache523    if (opts.cache) cache[name] = view;524  }525526  // render527  try {528    view.render(opts, fn);529  } catch (err) {530    fn(err);531  }532};