Skip to content
Myr

application.js

This file

Path

lib/application.js

572 lines · 11.8 KiB · JavaScript

Last changed by

app.path()Tj Holowaychukbefore adoption17a831e

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('env', process.env.NODE_ENV || 'development');8384  // implicit middleware85  this.use(connect.query());86  this.use(middleware.init(this));8788  // app locals89  this.locals = function(obj){90    for (var key in obj) self.locals[key] = obj[key];91    return self;92  };9394  // response locals95  this.locals.use = function(fn){96    if (3 == fn.length) {97      self.viewCallbacks.push(fn);98    } else {99      self.viewCallbacks.push(function(req, res, done){100        fn(req, res);101        done();102      });103    }104    return this;105  };106107  // router108  this._router = new Router(this);109  this.routes = this._router.routes;110  this.__defineGetter__('router', function(){111    this._usedRouter = true;112    return self._router.middleware;113  });114115  // default locals116  this.locals.settings = this.settings;117118  // default production configuration119  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 {Stirng} path141 * @return {Array}142 * @api public143 */144145app.lookup = function(path){146  return this._router.lookup('all', path);147};148149/**150 * Lookup routes matching the given `url`.151 *152 * @param {Stirng} url153 * @return {Array}154 * @api public155 */156157app.match = function(url){158  return this._router.match('all', url);159};160161/**162 * Proxy `connect#use()` to apply settings to163 * mounted applications.164 *165 * @param {String|Function|Server} route166 * @param {Function|Server} fn167 * @return {app} for chaining168 * @api public169 */170171app.use = function(route, fn){172  var app, home, handle;173174  // default route to '/'175  if ('string' != typeof route) fn = route, route = '/';176177  // express app178  if (fn.handle && fn.set) app = fn;179180  // restore .app property on req and res181  if (app) {182    app.route = route;183    fn = function(req, res, next) {184      var orig = req.app;185      app.handle(req, res, function(err){186        req.app = res.app = orig;187        next(err);188      });189    };190  }191192  connect.proto.use.call(this, route, fn);193194  // mounted an app195  if (app) {196    app.parent = this;197    app.emit('mount', this);198  }199200  return this;201};202203/**204 * Register the given template engine callback `fn`205 * as `ext`. For example we may wish to map ".html"206 * files to ejs rather than using the ".ejs" extension.207 *208 *    app.engine('.html', require('ejs').render);209 *210 * or211 *212 *    app.engine('html', require('ejs').render);213 *214 * @param {String} ext215 * @param {Function} fn216 * @return {app} for chaining217 * @api public218 */219220app.engine = function(ext, fn){221  if ('.' != ext[0]) ext = '.' + ext;222  this.engines[ext] = fn;223  return this;224};225226/**227 * Map the given param placeholder `name`(s) to the given callback(s).228 *229 * Param mapping is used to provide pre-conditions to routes230 * which us normalized placeholders. This callback has the same231 * signature as regular middleware, for example below when ":userId"232 * is used this function will be invoked in an attempt to load the user.233 *234 *      app.param('userId', function(req, res, next, id){235 *        User.find(id, function(err, user){236 *          if (err) {237 *            next(err);238 *          } else if (user) {239 *            req.user = user;240 *            next();241 *          } else {242 *            next(new Error('failed to load user'));243 *          }244 *        });245 *      });246 *247 * Passing a single function allows you to map logic248 * to the values passed to `app.param()`, for example249 * this is useful to provide coercion support in a concise manner.250 *251 * The following example maps regular expressions to param values252 * ensuring that they match, otherwise passing control to the next253 * route:254 *255 *      app.param(function(name, regexp){256 *        if (regexp instanceof RegExp) {257 *          return function(req, res, next, val){258 *            var captures;259 *            if (captures = regexp.exec(String(val))) {260 *              req.params[name] = captures;261 *              next();262 *            } else {263 *              next('route');264 *            }265 *          }266 *        }267 *      });268 *269 * We can now use it as shown below, where "/commit/:commit" expects270 * that the value for ":commit" is at 5 or more digits. The capture271 * groups are then available as `req.params.commit` as we defined272 * in the function above.273 *274 *    app.param('commit', /^\d{5,}$/);275 *276 * For more of this useful functionality take a look277 * at [express-params](http://github.com/visionmedia/express-params).278 *279 * @param {String|Array|Function} name280 * @param {Function} fn281 * @return {app} for chaining282 * @api public283 */284285app.param = function(name, fn){286  var self = this287    , fns = [].slice.call(arguments, 1);288289  // array290  if (Array.isArray(name)) {291    name.forEach(function(name){292      fns.forEach(function(fn){293        self.param(name, fn);294      });295    });296  // param logic297  } else if ('function' == typeof name) {298    this._router.param(name);299  // single300  } else {301    if (':' == name[0]) name = name.substr(1);302    fns.forEach(function(fn){303      self._router.param(name, fn);304    });305  }306307  return this;308};309310/**311 * Register the given callback `fn` for the given `type`.312 *313 * @param {String} type314 * @param {Function} fn315 * @return {app} for chaining316 * @api public317 */318319app.is = function(type, fn){320  if (!fn) return this.isCallbacks[type];321  this.isCallbacks[type] = fn;322  return this;323};324325/**326 * Assign `setting` to `val`, or return `setting`'s value.327 * Mounted servers inherit their parent server's settings.328 *329 * @param {String} setting330 * @param {String} val331 * @return {Server|Mixed} for chaining, or the setting value332 * @api public333 */334335app.set = function(setting, val){336  if (val === undefined) {337    if (this.settings.hasOwnProperty(setting)) {338      return this.settings[setting];339    } else if (this.parent) {340      return this.parent.set(setting);341    }342  } else {343    this.settings[setting] = val;344    return this;345  }346};347348/**349 * Return the app's absolute pathname350 * based on the parent(s) that have351 * mounted it.352 *353 * @return {String}354 * @api private355 */356357app.path = function(){358  return this.parent359    ? this.parent.path() + this.route360    : '';361};362363/**364 * Check if `setting` is enabled.365 *366 * @param {String} setting367 * @return {Boolean}368 * @api public369 */370371app.enabled = function(setting){372  return !!this.set(setting);373};374375/**376 * Check if `setting` is disabled.377 *378 * @param {String} setting379 * @return {Boolean}380 * @api public381 */382383app.disabled = function(setting){384  return !this.set(setting);385};386387/**388 * Enable `setting`.389 *390 * @param {String} setting391 * @return {app} for chaining392 * @api public393 */394395app.enable = function(setting){396  return this.set(setting, true);397};398399/**400 * Disable `setting`.401 *402 * @param {String} setting403 * @return {app} for chaining404 * @api public405 */406407app.disable = function(setting){408  return this.set(setting, false);409};410411/**412 * Redirect `key` to `url`.413 *414 * @param {String} key415 * @param {String} url416 * @return {app} for chaining417 * @api public418 */419420app.redirect = function(key, url){421  this.redirects[key] = url;422  return this;423};424425/**426 * Configure callback for zero or more envs,427 * when no env is specified that callback will428 * be invoked for all environments. Any combination429 * can be used multiple times, in any order desired.430 *431 * Examples:432 *433 *    app.configure(function(){434 *      // executed for all envs435 *    });436 *437 *    app.configure('stage', function(){438 *      // executed staging env439 *    });440 *441 *    app.configure('stage', 'production', function(){442 *      // executed for stage and production443 *    });444 *445 * @param {String} env...446 * @param {Function} fn447 * @return {app} for chaining448 * @api public449 */450451app.configure = function(env, fn){452  var envs = 'all'453    , args = [].slice.call(arguments);454  fn = args.pop();455  if (args.length) envs = args;456  if ('all' == envs || ~envs.indexOf(this.settings.env)) fn.call(this);457  return this;458};459460/**461 * Listen for connections.462 *463 * This method takes the same arguments464 * as node's `http.Server#listen()`.  465 *466 * @return {http.Server}467 * @api public468 */469470app.listen = function(){471  var server = http.createServer(this);472  return server.listen.apply(server, arguments);473};474475/**476 * Delegate `.VERB(...)` calls to `.route(VERB, ...)`.477 */478479methods.forEach(function(method){480  app[method] = function(path){481    if ('get' == method && 1 == arguments.length) return this.set(path); 482    var args = [method].concat([].slice.call(arguments));483    if (!this._usedRouter) this.use(this.router);484    return this._router._route.apply(this._router, args);485  }486});487488/**489 * Special-cased "all" method, applying the given route `path`,490 * middleware, and callback to _every_ HTTP method.491 *492 * @param {String} path493 * @param {Function} ...494 * @return {app} for chaining495 * @api public496 */497498app.all = function(path){499  var args = arguments;500  methods.forEach(function(method){501    if ('all' == method) return;502    app[method].apply(this, args);503  }, this);504  return this;505};506507// del -> delete alias508509app.del = app.delete;510511/**512 * Render the given view `name` name with `options`513 * and a callback accepting an error and the514 * rendered template string.515 *516 * @param {String} name517 * @param {String|Function} options or fn518 * @param {Function} fn519 * @api public520 */521522app.render = function(name, options, fn){523  var self = this524    , opts = {}525    , cache = this.cache526    , engines = this.engines527    , view;528529  // support callback function as second arg530  if ('function' == typeof options) {531    fn = options, options = {};532  }533534  // merge app.locals535  utils.merge(opts, this.locals);536537  // merge options.locals538  if (options.locals) {539    utils.merge(opts, options.locals);540    delete opts.locals;541  }542543  // merge options544  utils.merge(opts, options);545546  // set .cache unless explicitly provided547  opts.cache = null == opts.cache548    ? this.enabled('view cache')549    : opts.cache;550551  // primed cache552  if (opts.cache) view = cache[name];553554  // view555  if (!view) {556    view = new View(name, {557        defaultEngine: this.get('view engine')558      , root: this.get('views') || process.cwd() + '/views'559      , engines: engines560    });561562    // prime the cache563    if (opts.cache) cache[name] = view;564  }565566  // render567  try {568    view.render(opts, fn);569  } catch (err) {570    fn(err);571  }572};