Skip to content
Myr

application.js

This file

Path

lib/application.js

563 lines · 11.7 KiB · JavaScript

Last changed by

Added: emit "mount" event on the app being mountedTj Holowaychukbefore adoptionb6611c8

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  , View = require('./view')17  , url = require('url')18  , utils = connect.utils19  , path = require('path')20  , http = require('http')21  , join = path.join22  , fs = require('fs')23  , qs = require('qs');2425/**26 * Expose `HTTPServer`.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.redirects = {};47  this.isCallbacks = {};48  this.viewCallbacks = [];49  this.defaultConfiguration();5051  // route reflection methods52  methods.forEach(function(method){53    self.lookup[method] = function(path){54      return self._router.lookup(method, path);55    };5657    self.match[method] = function(path){58      return self._router.match(method, path);59    };6061    self.remove[method] = function(path){62      return self._router.lookup(method, path).remove();63    };64  });6566  // del -> delete67  self.lookup.del = self.lookup.delete;68  self.match.del = self.match.delete;69  self.remove.del = self.remove.delete;70};7172/**73 * Initialize application configuration.74 *75 * @api private76 */7778app.defaultConfiguration = function(){79  var self = this;8081  // default settings82  this.set('root', '/');83  this.set('env', process.env.NODE_ENV || 'development');8485  // implicit middleware86  this.use(connect.query());87  this.use(middleware.init(this));8889  // app locals90  this.locals = function(obj){91    for (var key in obj) self.locals[key] = obj[key];92    return self;93  };9495  // response locals96  this.locals.use = function(fn){97    if (3 == fn.length) {98      self.viewCallbacks.push(fn);99    } else {100      self.viewCallbacks.push(function(req, res, done){101        fn(req, res);102        done();103      });104    }105    return this;106  };107108109  // router110  this._router = new Router(this);111  this.routes = this._router.routes;112  this.__defineGetter__('router', function(){113    this._usedRouter = true;114    return self._router.middleware;115  });116117  // default locals118  this.locals.settings = this.settings;119120  // default production configuration121  this.configure('production', function(){122    this.enable('view cache');123  });124};125126/**127 * Remove routes matching the given `path`.128 *129 * @param {Route} path130 * @return {Boolean}131 * @api public132 */133134app.remove = function(path){135  return this._router.lookup('all', path).remove();136};137138/**139 * Lookup routes defined with a path140 * equivalent to `path`.141 *142 * @param {Stirng} path143 * @return {Array}144 * @api public145 */146147app.lookup = function(path){148  return this._router.lookup('all', path);149};150151/**152 * Lookup routes matching the given `url`.153 *154 * @param {Stirng} url155 * @return {Array}156 * @api public157 */158159app.match = function(url){160  return this._router.match('all', url);161};162163/**164 * Proxy `connect#use()` to apply settings to165 * mounted applications.166 *167 * @param {String|Function|Server} route168 * @param {Function|Server} fn169 * @return {app} for chaining170 * @api public171 */172173app.use = function(route, fn){174  var app, home, handle;175176  if ('string' != typeof route) fn = route, route = '/';177178  // express app179  if (fn.handle && fn.set) app = fn;180181  // restore .app property on req and res182  if (app) {183    app.route = route;184    fn = function(req, res, next) {185      var orig = req.app;186      app.handle(req, res, function(err){187        req.app = res.app = orig;188        next(err);189      });190    };191  }192193  connect.proto.use.call(this, route, fn);194195  // mounted an app, invoke the hook196  // and adjust some settings197  if (app) {198    var root = this.get('root') || this.route;199    if ('/' == root) root = '';200    root = root + (app.get('root') || app.route);201    app.set('root', root);202    app.parent = this;203    app.emit('mount', this);204  }205206  return this;207};208209/**210 * Register the given template engine callback `fn`211 * as `ext`. For example we may wish to map ".html"212 * files to ejs rather than using the ".ejs" extension.213 *214 *    app.engine('.html', require('ejs').render);215 *216 * or217 *218 *    app.engine('html', require('ejs').render);219 *220 * @param {String} ext221 * @param {Function} fn222 * @return {app} for chaining223 * @api public224 */225226app.engine = function(ext, fn){227  if ('.' != ext[0]) ext = '.' + ext;228  this.engines[ext] = fn;229  return this;230};231232/**233 * Map the given param placeholder `name`(s) to the given callback(s).234 *235 * Param mapping is used to provide pre-conditions to routes236 * which us normalized placeholders. This callback has the same237 * signature as regular middleware, for example below when ":userId"238 * is used this function will be invoked in an attempt to load the user.239 *240 *      app.param('userId', function(req, res, next, id){241 *        User.find(id, function(err, user){242 *          if (err) {243 *            next(err);244 *          } else if (user) {245 *            req.user = user;246 *            next();247 *          } else {248 *            next(new Error('failed to load user'));249 *          }250 *        });251 *      });252 *253 * Passing a single function allows you to map logic254 * to the values passed to `app.param()`, for example255 * this is useful to provide coercion support in a concise manner.256 *257 * The following example maps regular expressions to param values258 * ensuring that they match, otherwise passing control to the next259 * route:260 *261 *      app.param(function(name, regexp){262 *        if (regexp instanceof RegExp) {263 *          return function(req, res, next, val){264 *            var captures;265 *            if (captures = regexp.exec(String(val))) {266 *              req.params[name] = captures;267 *              next();268 *            } else {269 *              next('route');270 *            }271 *          }272 *        }273 *      });274 *275 * We can now use it as shown below, where "/commit/:commit" expects276 * that the value for ":commit" is at 5 or more digits. The capture277 * groups are then available as `req.params.commit` as we defined278 * in the function above.279 *280 *    app.param('commit', /^\d{5,}$/);281 *282 * For more of this useful functionality take a look283 * at [express-params](http://github.com/visionmedia/express-params).284 *285 * @param {String|Array|Function} name286 * @param {Function} fn287 * @return {app} for chaining288 * @api public289 */290291app.param = function(name, fn){292  var self = this293    , fns = [].slice.call(arguments, 1);294295  // array296  if (Array.isArray(name)) {297    name.forEach(function(name){298      fns.forEach(function(fn){299        self.param(name, fn);300      });301    });302  // param logic303  } else if ('function' == typeof name) {304    this._router.param(name);305  // single306  } else {307    if (':' == name[0]) name = name.substr(1);308    fns.forEach(function(fn){309      self._router.param(name, fn);310    });311  }312313  return this;314};315316/**317 * Register the given callback `fn` for the given `type`.318 *319 * @param {String} type320 * @param {Function} fn321 * @return {app} for chaining322 * @api public323 */324325app.is = function(type, fn){326  if (!fn) return this.isCallbacks[type];327  this.isCallbacks[type] = fn;328  return this;329};330331/**332 * Assign `setting` to `val`, or return `setting`'s value.333 * Mounted servers inherit their parent server's settings.334 *335 * @param {String} setting336 * @param {String} val337 * @return {Server|Mixed} for chaining, or the setting value338 * @api public339 */340341app.set = function(setting, val){342  if (val === undefined) {343    if (this.settings.hasOwnProperty(setting)) {344      return this.settings[setting];345    } else if (this.parent) {346      return this.parent.set(setting);347    }348  } else {349    this.settings[setting] = val;350    return this;351  }352};353354/**355 * Check if `setting` is enabled.356 *357 * @param {String} setting358 * @return {Boolean}359 * @api public360 */361362app.enabled = function(setting){363  return !!this.set(setting);364};365366/**367 * Check if `setting` is disabled.368 *369 * @param {String} setting370 * @return {Boolean}371 * @api public372 */373374app.disabled = function(setting){375  return !this.set(setting);376};377378/**379 * Enable `setting`.380 *381 * @param {String} setting382 * @return {app} for chaining383 * @api public384 */385386app.enable = function(setting){387  return this.set(setting, true);388};389390/**391 * Disable `setting`.392 *393 * @param {String} setting394 * @return {app} for chaining395 * @api public396 */397398app.disable = function(setting){399  return this.set(setting, false);400};401402/**403 * Redirect `key` to `url`.404 *405 * @param {String} key406 * @param {String} url407 * @return {app} for chaining408 * @api public409 */410411app.redirect = function(key, url){412  this.redirects[key] = url;413  return this;414};415416/**417 * Configure callback for zero or more envs,418 * when no env is specified that callback will419 * be invoked for all environments. Any combination420 * can be used multiple times, in any order desired.421 *422 * Examples:423 *424 *    app.configure(function(){425 *      // executed for all envs426 *    });427 *428 *    app.configure('stage', function(){429 *      // executed staging env430 *    });431 *432 *    app.configure('stage', 'production', function(){433 *      // executed for stage and production434 *    });435 *436 * @param {String} env...437 * @param {Function} fn438 * @return {app} for chaining439 * @api public440 */441442app.configure = function(env, fn){443  var envs = 'all'444    , args = [].slice.call(arguments);445  fn = args.pop();446  if (args.length) envs = args;447  if ('all' == envs || ~envs.indexOf(this.settings.env)) fn.call(this);448  return this;449};450451/**452 * Listen for connections.453 *454 * This method takes the same arguments455 * as node's `http.Server#listen()`.  456 *457 * @return {http.Server}458 * @api public459 */460461app.listen = function(){462  var server = http.createServer(this);463  return server.listen.apply(server, arguments);464};465466/**467 * Delegate `.VERB(...)` calls to `.route(VERB, ...)`.468 */469470methods.forEach(function(method){471  app[method] = function(path){472    if ('get' == method && 1 == arguments.length) return this.set(path); 473    var args = [method].concat([].slice.call(arguments));474    if (!this._usedRouter) this.use(this.router);475    return this._router._route.apply(this._router, args);476  }477});478479/**480 * Special-cased "all" method, applying the given route `path`,481 * middleware, and callback to _every_ HTTP method.482 *483 * @param {String} path484 * @param {Function} ...485 * @return {app} for chaining486 * @api public487 */488489app.all = function(path){490  var args = arguments;491  methods.forEach(function(method){492    if ('all' == method) return;493    app[method].apply(this, args);494  }, this);495  return this;496};497498// del -> delete alias499500app.del = app.delete;501502/**503 * Render the given view `name` name with `options`504 * and a callback accepting an error and the505 * rendered template string.506 *507 * @param {String} name508 * @param {String|Function} options or fn509 * @param {Function} fn510 * @api public511 */512513app.render = function(name, options, fn){514  var self = this515    , opts = {}516    , cache = this.cache517    , engines = this.engines518    , view;519520  // support callback function as second arg521  if ('function' == typeof options) {522    fn = options, options = {};523  }524525  // merge app.locals526  utils.merge(opts, this.locals);527528  // merge options.locals529  if (options.locals) {530    utils.merge(opts, options.locals);531    delete opts.locals;532  }533534  // merge options535  utils.merge(opts, options);536537  // set .cache unless explicitly provided538  opts.cache = null == opts.cache539    ? this.enabled('view cache')540    : opts.cache;541542  // primed cache543  if (opts.cache) view = cache[name];544545  // view546  if (!view) {547    view = new View(name, {548        defaultEngine: this.get('view engine')549      , root: this.get('views') || process.cwd() + '/views'550      , engines: engines551    });552553    // prime the cache554    if (opts.cache) cache[name] = view;555  }556557  // render558  try {559    view.render(opts, fn);560  } catch (err) {561    fn(err);562  }563};