Skip to content
Myr

application.js

This file

Path

lib/application.js

525 lines · 11.1 KiB · JavaScript

Last changed by

Merge pull request #968 from peters/patch-1TJ Holowaychukbefore adoption4eb8bc0

History of this file

Take it

1/*!2 * Express - proto3 * Copyright(c) 2010 TJ Holowaychuk <tj@vision-media.ca>4 * MIT Licensed5 */67/**8 * Module dependencies.9 */1011var connect = require('connect')12  , Router = require('./router')13  , methods = Router.methods.concat('del', 'all')14  , middleware = require('./middleware')15  , View = require('./view')16  , url = require('url')17  , utils = connect.utils18  , path = require('path')19  , http = require('http')20  , join = path.join21  , fs = require('fs')22  , qs = require('qs');2324/**25 * Application prototype.26 */2728var app = exports = module.exports = {};2930/**31 * Initialize the server.32 *33 *   - setup default configuration34 *   - setup default middleware35 *   - setup route reflection methods36 *37 * @api private38 */3940app.init = function(){41  var self = this;42  this.cache = {};43  this.settings = {};44  this.engines = {};45  this.viewCallbacks = [];46  this.defaultConfiguration();4748  // route reflection methods49  methods.forEach(function(method){50    self.lookup[method] = function(path){51      return self._router.lookup(method, path);52    };5354    self.remove[method] = function(path){55      return self._router.lookup(method, path).remove();56    };57  });5859  // del -> delete60  self.lookup.del = self.lookup.delete;61  self.remove.del = self.remove.delete;62};6364/**65 * Initialize application configuration.66 *67 * @api private68 */6970app.defaultConfiguration = function(){71  var self = this;7273  // default settings74  this.set('env', process.env.NODE_ENV || 'development');7576  // implicit middleware77  this.use(connect.query());78  this.use(middleware.init(this));7980  // app locals81  this.locals = function(obj){82    for (var key in obj) self.locals[key] = obj[key];83    return self;84  };8586  // response locals87  this.locals.use = function(fn){88    if (3 == fn.length) {89      self.viewCallbacks.push(fn);90    } else {91      self.viewCallbacks.push(function(req, res, done){92        fn(req, res);93        done();94      });95    }96    return this;97  };9899  // router100  this._router = new Router(this);101  this.routes = this._router.routes;102  this.__defineGetter__('router', function(){103    this._usedRouter = true;104    this._router.caseSensitive = this.enabled('case sensitive routing');105    this._router.strict = this.enabled('strict routing');106    return this._router.middleware;107  });108109  // default locals110  this.locals.settings = this.settings;111112  // default production configuration113  this.configure('production', function(){114    this.enable('view cache');115  });116};117118/**119 * Remove routes matching the given `path`.120 *121 * @param {Route} path122 * @return {Boolean}123 * @api public124 */125126app.remove = function(path){127  return this._router.lookup('all', path).remove();128};129130/**131 * Lookup routes defined with a path132 * equivalent to `path`.133 *134 * @param {String} path135 * @return {Array}136 * @api public137 */138139app.lookup = function(path){140  return this._router.lookup('all', path);141};142143/**144 * Proxy `connect#use()` to apply settings to145 * mounted applications.146 *147 * @param {String|Function|Server} route148 * @param {Function|Server} fn149 * @return {app} for chaining150 * @api public151 */152153app.use = function(route, fn){154  var app, home, handle;155156  // default route to '/'157  if ('string' != typeof route) fn = route, route = '/';158159  // express app160  if (fn.handle && fn.set) app = fn;161162  // restore .app property on req and res163  if (app) {164    app.route = route;165    fn = function(req, res, next) {166      var orig = req.app;167      app.handle(req, res, function(err){168        req.app = res.app = orig;169        next(err);170      });171    };172  }173174  connect.proto.use.call(this, route, fn);175176  // mounted an app177  if (app) {178    app.parent = this;179    app.emit('mount', this);180  }181182  return this;183};184185/**186 * Register the given template engine callback `fn`187 * as `ext`. For example we may wish to map ".html"188 * files to ejs rather than using the ".ejs" extension.189 *190 *    app.engine('.html', require('ejs').render);191 *192 * or193 *194 *    app.engine('html', require('ejs').render);195 *196 * @param {String} ext197 * @param {Function} fn198 * @return {app} for chaining199 * @api public200 */201202app.engine = function(ext, fn){203  if ('.' != ext[0]) ext = '.' + ext;204  this.engines[ext] = fn;205  return this;206};207208/**209 * Map the given param placeholder `name`(s) to the given callback(s).210 *211 * Param mapping is used to provide pre-conditions to routes212 * which us normalized placeholders. This callback has the same213 * signature as regular middleware, for example below when ":userId"214 * is used this function will be invoked in an attempt to load the user.215 *216 *      app.param('userId', function(req, res, next, id){217 *        User.find(id, function(err, user){218 *          if (err) {219 *            next(err);220 *          } else if (user) {221 *            req.user = user;222 *            next();223 *          } else {224 *            next(new Error('failed to load user'));225 *          }226 *        });227 *      });228 *229 * Passing a single function allows you to map logic230 * to the values passed to `app.param()`, for example231 * this is useful to provide coercion support in a concise manner.232 *233 * The following example maps regular expressions to param values234 * ensuring that they match, otherwise passing control to the next235 * route:236 *237 *      app.param(function(name, regexp){238 *        if (regexp instanceof RegExp) {239 *          return function(req, res, next, val){240 *            var captures;241 *            if (captures = regexp.exec(String(val))) {242 *              req.params[name] = captures;243 *              next();244 *            } else {245 *              next('route');246 *            }247 *          }248 *        }249 *      });250 *251 * We can now use it as shown below, where "/commit/:commit" expects252 * that the value for ":commit" is at 5 or more digits. The capture253 * groups are then available as `req.params.commit` as we defined254 * in the function above.255 *256 *    app.param('commit', /^\d{5,}$/);257 *258 * For more of this useful functionality take a look259 * at [express-params](http://github.com/visionmedia/express-params).260 *261 * @param {String|Array|Function} name262 * @param {Function} fn263 * @return {app} for chaining264 * @api public265 */266267app.param = function(name, fn){268  var self = this269    , fns = [].slice.call(arguments, 1);270271  // array272  if (Array.isArray(name)) {273    name.forEach(function(name){274      fns.forEach(function(fn){275        self.param(name, fn);276      });277    });278  // param logic279  } else if ('function' == typeof name) {280    this._router.param(name);281  // single282  } else {283    if (':' == name[0]) name = name.substr(1);284    fns.forEach(function(fn){285      self._router.param(name, fn);286    });287  }288289  return this;290};291292/**293 * Assign `setting` to `val`, or return `setting`'s value.294 * Mounted servers inherit their parent server's settings.295 *296 * @param {String} setting297 * @param {String} val298 * @return {Server|Mixed} for chaining, or the setting value299 * @api public300 */301302app.set = function(setting, val){303  if (1 == arguments.length) {304    if (this.settings.hasOwnProperty(setting)) {305      return this.settings[setting];306    } else if (this.parent) {307      return this.parent.set(setting);308    }309  } else {310    this.settings[setting] = val;311    return this;312  }313};314315/**316 * Return the app's absolute pathname317 * based on the parent(s) that have318 * mounted it.319 *320 * @return {String}321 * @api private322 */323324app.path = function(){325  return this.parent326    ? this.parent.path() + this.route327    : '';328};329330/**331 * Check if `setting` is enabled.332 *333 * @param {String} setting334 * @return {Boolean}335 * @api public336 */337338app.enabled = function(setting){339  return !!this.set(setting);340};341342/**343 * Check if `setting` is disabled.344 *345 * @param {String} setting346 * @return {Boolean}347 * @api public348 */349350app.disabled = function(setting){351  return !this.set(setting);352};353354/**355 * Enable `setting`.356 *357 * @param {String} setting358 * @return {app} for chaining359 * @api public360 */361362app.enable = function(setting){363  return this.set(setting, true);364};365366/**367 * Disable `setting`.368 *369 * @param {String} setting370 * @return {app} for chaining371 * @api public372 */373374app.disable = function(setting){375  return this.set(setting, false);376};377378/**379 * Configure callback for zero or more envs,380 * when no env is specified that callback will381 * be invoked for all environments. Any combination382 * can be used multiple times, in any order desired.383 *384 * Examples:385 *386 *    app.configure(function(){387 *      // executed for all envs388 *    });389 *390 *    app.configure('stage', function(){391 *      // executed staging env392 *    });393 *394 *    app.configure('stage', 'production', function(){395 *      // executed for stage and production396 *    });397 *398 * @param {String} env...399 * @param {Function} fn400 * @return {app} for chaining401 * @api public402 */403404app.configure = function(env, fn){405  var envs = 'all'406    , args = [].slice.call(arguments);407  fn = args.pop();408  if (args.length) envs = args;409  if ('all' == envs || ~envs.indexOf(this.settings.env)) fn.call(this);410  return this;411};412413/**414 * Listen for connections.415 *416 * This method takes the same arguments417 * as node's `http.Server#listen()`.  418 *419 * @return {http.Server}420 * @api public421 */422423app.listen = function(){424  var server = http.createServer(this);425  return server.listen.apply(server, arguments);426};427428/**429 * Delegate `.VERB(...)` calls to `.route(VERB, ...)`.430 */431432methods.forEach(function(method){433  app[method] = function(path){434    if ('get' == method && 1 == arguments.length) return this.set(path); 435    var args = [method].concat([].slice.call(arguments));436    if (!this._usedRouter) this.use(this.router);437    return this._router.route.apply(this._router, args);438  }439});440441/**442 * Special-cased "all" method, applying the given route `path`,443 * middleware, and callback to _every_ HTTP method.444 *445 * @param {String} path446 * @param {Function} ...447 * @return {app} for chaining448 * @api public449 */450451app.all = function(path){452  var args = arguments;453  methods.forEach(function(method){454    if ('all' == method) return;455    app[method].apply(this, args);456  }, this);457  return this;458};459460// del -> delete alias461462app.del = app.delete;463464/**465 * Render the given view `name` name with `options`466 * and a callback accepting an error and the467 * rendered template string.468 *469 * @param {String} name470 * @param {String|Function} options or fn471 * @param {Function} fn472 * @api public473 */474475app.render = function(name, options, fn){476  var self = this477    , opts = {}478    , cache = this.cache479    , engines = this.engines480    , view;481482  // support callback function as second arg483  if ('function' == typeof options) {484    fn = options, options = {};485  }486487  // merge app.locals488  utils.merge(opts, this.locals);489490  // merge options.locals491  if (options.locals) {492    utils.merge(opts, options.locals);493    delete opts.locals;494  }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    // prime the cache516    if (opts.cache) cache[name] = view;517  }518519  // render520  try {521    view.render(opts, fn);522  } catch (err) {523    fn(err);524  }525};