Skip to content
Myr

application.js

This file

Path

lib/application.js

557 lines · 11.5 KiB · JavaScript

Last changed by

Removed `app.redirect()`Tj Holowaychukbefore adoption4329528

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.isCallbacks = {};47  this.viewCallbacks = [];48  this.defaultConfiguration();4950  // route reflection methods51  methods.forEach(function(method){52    self.lookup[method] = function(path){53      return self._router.lookup(method, path);54    };5556    self.match[method] = function(path){57      return self._router.match(method, path);58    };5960    self.remove[method] = function(path){61      return self._router.lookup(method, path).remove();62    };63  });6465  // del -> delete66  self.lookup.del = self.lookup.delete;67  self.match.del = self.match.delete;68  self.remove.del = self.remove.delete;69};7071/**72 * Initialize application configuration.73 *74 * @api private75 */7677app.defaultConfiguration = function(){78  var self = this;7980  // default settings81  this.set('env', process.env.NODE_ENV || 'development');8283  // implicit middleware84  this.use(connect.query());85  this.use(middleware.init(this));8687  // app locals88  this.locals = function(obj){89    for (var key in obj) self.locals[key] = obj[key];90    return self;91  };9293  // response locals94  this.locals.use = function(fn){95    if (3 == fn.length) {96      self.viewCallbacks.push(fn);97    } else {98      self.viewCallbacks.push(function(req, res, done){99        fn(req, res);100        done();101      });102    }103    return this;104  };105106  // router107  this._router = new Router(this);108  this.routes = this._router.routes;109  this.__defineGetter__('router', function(){110    this._usedRouter = true;111    return self._router.middleware;112  });113114  // default locals115  this.locals.settings = this.settings;116117  // default production configuration118  this.configure('production', function(){119    this.enable('view cache');120  });121};122123/**124 * Remove routes matching the given `path`.125 *126 * @param {Route} path127 * @return {Boolean}128 * @api public129 */130131app.remove = function(path){132  return this._router.lookup('all', path).remove();133};134135/**136 * Lookup routes defined with a path137 * equivalent to `path`.138 *139 * @param {Stirng} path140 * @return {Array}141 * @api public142 */143144app.lookup = function(path){145  return this._router.lookup('all', path);146};147148/**149 * Lookup routes matching the given `url`.150 *151 * @param {Stirng} url152 * @return {Array}153 * @api public154 */155156app.match = function(url){157  return this._router.match('all', url);158};159160/**161 * Proxy `connect#use()` to apply settings to162 * mounted applications.163 *164 * @param {String|Function|Server} route165 * @param {Function|Server} fn166 * @return {app} for chaining167 * @api public168 */169170app.use = function(route, fn){171  var app, home, handle;172173  // default route to '/'174  if ('string' != typeof route) fn = route, route = '/';175176  // express app177  if (fn.handle && fn.set) app = fn;178179  // restore .app property on req and res180  if (app) {181    app.route = route;182    fn = function(req, res, next) {183      var orig = req.app;184      app.handle(req, res, function(err){185        req.app = res.app = orig;186        next(err);187      });188    };189  }190191  connect.proto.use.call(this, route, fn);192193  // mounted an app194  if (app) {195    app.parent = this;196    app.emit('mount', this);197  }198199  return this;200};201202/**203 * Register the given template engine callback `fn`204 * as `ext`. For example we may wish to map ".html"205 * files to ejs rather than using the ".ejs" extension.206 *207 *    app.engine('.html', require('ejs').render);208 *209 * or210 *211 *    app.engine('html', require('ejs').render);212 *213 * @param {String} ext214 * @param {Function} fn215 * @return {app} for chaining216 * @api public217 */218219app.engine = function(ext, fn){220  if ('.' != ext[0]) ext = '.' + ext;221  this.engines[ext] = fn;222  return this;223};224225/**226 * Map the given param placeholder `name`(s) to the given callback(s).227 *228 * Param mapping is used to provide pre-conditions to routes229 * which us normalized placeholders. This callback has the same230 * signature as regular middleware, for example below when ":userId"231 * is used this function will be invoked in an attempt to load the user.232 *233 *      app.param('userId', function(req, res, next, id){234 *        User.find(id, function(err, user){235 *          if (err) {236 *            next(err);237 *          } else if (user) {238 *            req.user = user;239 *            next();240 *          } else {241 *            next(new Error('failed to load user'));242 *          }243 *        });244 *      });245 *246 * Passing a single function allows you to map logic247 * to the values passed to `app.param()`, for example248 * this is useful to provide coercion support in a concise manner.249 *250 * The following example maps regular expressions to param values251 * ensuring that they match, otherwise passing control to the next252 * route:253 *254 *      app.param(function(name, regexp){255 *        if (regexp instanceof RegExp) {256 *          return function(req, res, next, val){257 *            var captures;258 *            if (captures = regexp.exec(String(val))) {259 *              req.params[name] = captures;260 *              next();261 *            } else {262 *              next('route');263 *            }264 *          }265 *        }266 *      });267 *268 * We can now use it as shown below, where "/commit/:commit" expects269 * that the value for ":commit" is at 5 or more digits. The capture270 * groups are then available as `req.params.commit` as we defined271 * in the function above.272 *273 *    app.param('commit', /^\d{5,}$/);274 *275 * For more of this useful functionality take a look276 * at [express-params](http://github.com/visionmedia/express-params).277 *278 * @param {String|Array|Function} name279 * @param {Function} fn280 * @return {app} for chaining281 * @api public282 */283284app.param = function(name, fn){285  var self = this286    , fns = [].slice.call(arguments, 1);287288  // array289  if (Array.isArray(name)) {290    name.forEach(function(name){291      fns.forEach(function(fn){292        self.param(name, fn);293      });294    });295  // param logic296  } else if ('function' == typeof name) {297    this._router.param(name);298  // single299  } else {300    if (':' == name[0]) name = name.substr(1);301    fns.forEach(function(fn){302      self._router.param(name, fn);303    });304  }305306  return this;307};308309/**310 * Register the given callback `fn` for the given `type`.311 *312 * @param {String} type313 * @param {Function} fn314 * @return {app} for chaining315 * @api public316 */317318app.is = function(type, fn){319  if (!fn) return this.isCallbacks[type];320  this.isCallbacks[type] = fn;321  return this;322};323324/**325 * Assign `setting` to `val`, or return `setting`'s value.326 * Mounted servers inherit their parent server's settings.327 *328 * @param {String} setting329 * @param {String} val330 * @return {Server|Mixed} for chaining, or the setting value331 * @api public332 */333334app.set = function(setting, val){335  if (val === undefined) {336    if (this.settings.hasOwnProperty(setting)) {337      return this.settings[setting];338    } else if (this.parent) {339      return this.parent.set(setting);340    }341  } else {342    this.settings[setting] = val;343    return this;344  }345};346347/**348 * Return the app's absolute pathname349 * based on the parent(s) that have350 * mounted it.351 *352 * @return {String}353 * @api private354 */355356app.path = function(){357  return this.parent358    ? this.parent.path() + this.route359    : '';360};361362/**363 * Check if `setting` is enabled.364 *365 * @param {String} setting366 * @return {Boolean}367 * @api public368 */369370app.enabled = function(setting){371  return !!this.set(setting);372};373374/**375 * Check if `setting` is disabled.376 *377 * @param {String} setting378 * @return {Boolean}379 * @api public380 */381382app.disabled = function(setting){383  return !this.set(setting);384};385386/**387 * Enable `setting`.388 *389 * @param {String} setting390 * @return {app} for chaining391 * @api public392 */393394app.enable = function(setting){395  return this.set(setting, true);396};397398/**399 * Disable `setting`.400 *401 * @param {String} setting402 * @return {app} for chaining403 * @api public404 */405406app.disable = function(setting){407  return this.set(setting, false);408};409410/**411 * Configure callback for zero or more envs,412 * when no env is specified that callback will413 * be invoked for all environments. Any combination414 * can be used multiple times, in any order desired.415 *416 * Examples:417 *418 *    app.configure(function(){419 *      // executed for all envs420 *    });421 *422 *    app.configure('stage', function(){423 *      // executed staging env424 *    });425 *426 *    app.configure('stage', 'production', function(){427 *      // executed for stage and production428 *    });429 *430 * @param {String} env...431 * @param {Function} fn432 * @return {app} for chaining433 * @api public434 */435436app.configure = function(env, fn){437  var envs = 'all'438    , args = [].slice.call(arguments);439  fn = args.pop();440  if (args.length) envs = args;441  if ('all' == envs || ~envs.indexOf(this.settings.env)) fn.call(this);442  return this;443};444445/**446 * Listen for connections.447 *448 * This method takes the same arguments449 * as node's `http.Server#listen()`.  450 *451 * @return {http.Server}452 * @api public453 */454455app.listen = function(){456  var server = http.createServer(this);457  return server.listen.apply(server, arguments);458};459460/**461 * Delegate `.VERB(...)` calls to `.route(VERB, ...)`.462 */463464methods.forEach(function(method){465  app[method] = function(path){466    if ('get' == method && 1 == arguments.length) return this.set(path); 467    var args = [method].concat([].slice.call(arguments));468    if (!this._usedRouter) this.use(this.router);469    return this._router._route.apply(this._router, args);470  }471});472473/**474 * Special-cased "all" method, applying the given route `path`,475 * middleware, and callback to _every_ HTTP method.476 *477 * @param {String} path478 * @param {Function} ...479 * @return {app} for chaining480 * @api public481 */482483app.all = function(path){484  var args = arguments;485  methods.forEach(function(method){486    if ('all' == method) return;487    app[method].apply(this, args);488  }, this);489  return this;490};491492// del -> delete alias493494app.del = app.delete;495496/**497 * Render the given view `name` name with `options`498 * and a callback accepting an error and the499 * rendered template string.500 *501 * @param {String} name502 * @param {String|Function} options or fn503 * @param {Function} fn504 * @api public505 */506507app.render = function(name, options, fn){508  var self = this509    , opts = {}510    , cache = this.cache511    , engines = this.engines512    , view;513514  // support callback function as second arg515  if ('function' == typeof options) {516    fn = options, options = {};517  }518519  // merge app.locals520  utils.merge(opts, this.locals);521522  // merge options.locals523  if (options.locals) {524    utils.merge(opts, options.locals);525    delete opts.locals;526  }527528  // merge options529  utils.merge(opts, options);530531  // set .cache unless explicitly provided532  opts.cache = null == opts.cache533    ? this.enabled('view cache')534    : opts.cache;535536  // primed cache537  if (opts.cache) view = cache[name];538539  // view540  if (!view) {541    view = new View(name, {542        defaultEngine: this.get('view engine')543      , root: this.get('views') || process.cwd() + '/views'544      , engines: engines545    });546547    // prime the cache548    if (opts.cache) cache[name] = view;549  }550551  // render552  try {553    view.render(opts, fn);554  } catch (err) {555    fn(err);556  }557};