Skip to content
Myr

application.js

This file

Path

lib/application.js

594 lines · 12.5 KiB · JavaScript

Last changed by

misc refactoringTj Holowaychukbefore adoption4ed92d5

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  , toArray = require('./utils').toArray15  , methods = Router.methods.concat('del', 'all')16  , res = require('./response')17  , View = require('./view')18  , url = require('url')19  , utils = connect.utils20  , path = require('path')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.defaultConfiguration();4950  // route manipulation methods51  methods.forEach(function(method){52    self.lookup[method] = function(path){53      return self.routes.lookup(method, path);54    };5556    self.match[method] = function(path){57      return self.routes.match(method, path);58    };5960    self.remove[method] = function(path){61      return self.routes.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('home', '/');82  this.set('env', process.env.NODE_ENV || 'development');8384  // always parse req.query85  this.use(connect.query());8687  this.locals = function(obj){88    for (var key in obj) self.locals[key] = obj[key];89    return self;90  };9192  // expose objects to each other93  this.use(function(req, res, next){94    var charset;95    res.setHeader('X-Powered-By', 'Express');96    req.app = res.app = self;97    req.res = res;98    res.req = req;99    req.next = next;100101    // charset102    if (charset = self.set('charset')) res.charset = charset;103104    res.locals = function(obj){105      for (var key in obj) res.locals[key] = obj[key];106      return res;107    };108109    next();110  });111112  // router113  this.routes = new Router(this);114  this.__defineGetter__('router', function(){115    this.__usedRouter = true;116    return self.routes.middleware;117  });118119  // default locals120  this.locals.settings = this.settings;121122  // default production configuration123  this.configure('production', function(){124    this.enable('view cache');125  });126};127128/**129 * Remove routes matching the given `path`.130 *131 * @param {Route} path132 * @return {Boolean}133 * @api public134 */135136app.remove = function(path){137  return this.routes.lookup('all', path).remove();138};139140/**141 * Lookup routes defined with a path142 * equivalent to `path`.143 *144 * @param {Stirng} path145 * @return {Array}146 * @api public147 */148149app.lookup = function(path){150  return this.routes.lookup('all', path);151};152153/**154 * Lookup routes matching the given `url`.155 *156 * @param {Stirng} url157 * @return {Array}158 * @api public159 */160161app.match = function(url){162  return this.routes.match('all', url);163};164165/**166 * Proxy `connect.HTTPServer#use()` to apply settings to167 * mounted applications.168 *169 * @param {String|Function|Server} route170 * @param {Function|Server} middleware171 * @return {Server} for chaining172 * @api public173 */174175app.use = function(route, middleware){176  var app, home, handle;177178  if ('string' != typeof route) {179    middleware = route, route = '/';180  }181182  // express app183  if (middleware.handle && middleware.set) app = middleware;184185  // restore .app property on req and res186  if (app) {187    app.route = route;188    middleware = function(req, res, next) {189      var orig = req.app;190      app.handle(req, res, function(err){191        req.app = res.app = orig;192        next(err);193      });194    };195  }196197  connect.proto.use.call(this, route, middleware);198199  // mounted an app, invoke the hook200  // and adjust some settings201  if (app) {202    base = this.set('basepath') || this.route;203    if ('/' == base) base = '';204    base = base + (app.set('basepath') || app.route);205    app.set('basepath', base);206    app.parent = this;207    if (app.__mounted) app.__mounted.call(app, this);208  }209210  return this;211};212213/**214 * Assign a callback `fn` which is called215 * when this `Server` is passed to `Server#use()`.216 *217 * Examples:218 *219 *    var app = express.createServer()220 *      , blog = express.createServer();221 *222 *    blog.mounted(function(parent){223 *      // parent is app224 *      // "this" is blog225 *    });226 *227 *    app.use(blog);228 *229 * @param {Function} fn230 * @return {Server} for chaining231 * @api public232 */233234app.mounted = function(fn){235  this.__mounted = fn;236  return this;237};238239/**240 * Register the given template engine callback `fn`241 * as `ext`. For example we may wish to map ".html"242 * files to ejs rather than using the ".ejs" extension.243 *244 *    app.register('.html', require('ejs').render);245 *246 * or247 *248 *    app.register('html', require('ejs').render);249 *250 * @param {String} ext251 * @param {Function} fn252 * @return {Server} for chaining253 * @api public254 */255256app.register = function(ext, fn){257  if ('.' != ext[0]) ext = '.' + ext;258  this.engines[ext] = fn;259  return this;260};261262/**263 * Map the given param placeholder `name`(s) to the given callback `fn`.264 * Register the given view helpers `obj`. This method265 * can be called several times to apply additional helpers.266 *267 * @param {Object} obj268 * @return {Server} for chaining269 * @api public270 */271272app.locals = function(obj){273  utils.merge(this._locals, obj);274  return this;275};276277/**278 * Map the given param placeholder `name`(s) to the given callback(s).279 *280 * Param mapping is used to provide pre-conditions to routes281 * which us normalized placeholders. This callback has the same282 * signature as regular middleware, for example below when ":userId"283 * is used this function will be invoked in an attempt to load the user.284 *285 *      app.param('userId', function(req, res, next, id){286 *        User.find(id, function(err, user){287 *          if (err) {288 *            next(err);289 *          } else if (user) {290 *            req.user = user;291 *            next();292 *          } else {293 *            next(new Error('failed to load user'));294 *          }295 *        });296 *      });297 *298 * Passing a single function allows you to map logic299 * to the values passed to `app.param()`, for example300 * this is useful to provide coercion support in a concise manner.301 *302 * The following example maps regular expressions to param values303 * ensuring that they match, otherwise passing control to the next304 * route:305 *306 *      app.param(function(name, regexp){307 *        if (regexp instanceof RegExp) {308 *          return function(req, res, next, val){309 *            var captures;310 *            if (captures = regexp.exec(String(val))) {311 *              req.params[name] = captures;312 *              next();313 *            } else {314 *              next('route');315 *            }316 *          }317 *        }318 *      });319 *320 * We can now use it as shown below, where "/commit/:commit" expects321 * that the value for ":commit" is at 5 or more digits. The capture322 * groups are then available as `req.params.commit` as we defined323 * in the function above.324 *325 *    app.param('commit', /^\d{5,}$/);326 *327 * For more of this useful functionality take a look328 * at [express-params](http://github.com/visionmedia/express-params).329 *330 * @param {String|Array|Function} name331 * @param {Function} fn332 * @return {Server} for chaining333 * @api public334 */335336app.param = function(name, fn){337  var self = this338    , fns = [].slice.call(arguments, 1);339340  // array341  if (Array.isArray(name)) {342    name.forEach(function(name){343      fns.forEach(function(fn){344        self.param(name, fn);345      });346    });347  // param logic348  } else if ('function' == typeof name) {349    this.routes.param(name);350  // single351  } else {352    if (':' == name[0]) name = name.substr(1);353    fns.forEach(function(fn){354      self.routes.param(name, fn);355    });356  }357358  return this;359};360361/**362 * Register the given callback `fn` for the given `type`.363 *364 * @param {String} type365 * @param {Function} fn366 * @return {Server} for chaining367 * @api public368 */369370app.is = function(type, fn){371  if (!fn) return this.isCallbacks[type];372  this.isCallbacks[type] = fn;373  return this;374};375376/**377 * Assign `setting` to `val`, or return `setting`'s value.378 * Mounted servers inherit their parent server's settings.379 *380 * @param {String} setting381 * @param {String} val382 * @return {Server|Mixed} for chaining, or the setting value383 * @api public384 */385386app.set = function(setting, val){387  if (val === undefined) {388    if (this.settings.hasOwnProperty(setting)) {389      return this.settings[setting];390    } else if (this.parent) {391      return this.parent.set(setting);392    }393  } else {394    this.settings[setting] = val;395    return this;396  }397};398399/**400 * Check if `setting` is enabled.401 *402 * @param {String} setting403 * @return {Boolean}404 * @api public405 */406407app.enabled = function(setting){408  return !!this.set(setting);409};410411/**412 * Check if `setting` is disabled.413 *414 * @param {String} setting415 * @return {Boolean}416 * @api public417 */418419app.disabled = function(setting){420  return !this.set(setting);421};422423/**424 * Enable `setting`.425 *426 * @param {String} setting427 * @return {Server} for chaining428 * @api public429 */430431app.enable = function(setting){432  return this.set(setting, true);433};434435/**436 * Disable `setting`.437 *438 * @param {String} setting439 * @return {Server} for chaining440 * @api public441 */442443app.disable = function(setting){444  return this.set(setting, false);445};446447/**448 * Redirect `key` to `url`.449 *450 * @param {String} key451 * @param {String} url452 * @return {Server} for chaining453 * @api public454 */455456app.redirect = function(key, url){457  this.redirects[key] = url;458  return this;459};460461/**462 * Configure callback for zero or more envs,463 * when no env is specified that callback will464 * be invoked for all environments. Any combination465 * can be used multiple times, in any order desired.466 *467 * Examples:468 *469 *    app.configure(function(){470 *      // executed for all envs471 *    });472 *473 *    app.configure('stage', function(){474 *      // executed staging env475 *    });476 *477 *    app.configure('stage', 'production', function(){478 *      // executed for stage and production479 *    });480 *481 * @param {String} env...482 * @param {Function} fn483 * @return {Server} for chaining484 * @api public485 */486487app.configure = function(env, fn){488  var envs = 'all'489    , args = toArray(arguments);490  fn = args.pop();491  if (args.length) envs = args;492  if ('all' == envs || ~envs.indexOf(this.settings.env)) fn.call(this);493  return this;494};495496/**497 * Delegate `.VERB(...)` calls to `.route(VERB, ...)`.498 */499500methods.forEach(function(method){501  app[method] = function(path){502    if (1 == arguments.length) return this.routes.lookup(method, path);503    var args = [method].concat(toArray(arguments));504    if (!this.__usedRouter) this.use(this.router);505    return this.routes._route.apply(this.routes, args);506  }507});508509/**510 * Special-cased "all" method, applying the given route `path`,511 * middleware, and callback to _every_ HTTP method.512 *513 * @param {String} path514 * @param {Function} ...515 * @return {Server} for chaining516 * @api public517 */518519app.all = function(path){520  var args = arguments;521  if (1 == args.length) return this.routes.lookup('all', path);522  methods.forEach(function(method){523    if ('all' == method) return;524    app[method].apply(this, args);525  }, this);526  return this;527};528529// del -> delete alias530531app.del = app.delete;532533/**534 * Render the given view `name` name with `options`535 * and a callback accepting an error and the536 * rendered template string.537 *538 * @param {String} name539 * @param {String|Function} options or fn540 * @param {Function} fn541 * @api public542 */543544app.render = function(name, options, fn){545  var self = this546    , opts = {}547    , cache = this.cache548    , engines = this.engines549    , view;550551  // support callback function as second arg552  if ('function' == typeof options) {553    fn = options, options = {};554  }555556  // merge app.locals557  utils.merge(opts, this.locals);558559  // merge options.locals560  if (options.locals) {561    utils.merge(opts, options.locals);562    delete opts.locals;563  }564565  // merge options566  utils.merge(opts, options);567568  // set .cache unless explicitly provided569  opts.cache = null == opts.cache570    ? this.enabled('view cache')571    : opts.cache;572573  // primed cache574  if (opts.cache) view = cache[name];575576  // view577  if (!view) {578    view = new View(name, {579        defaultEngine: this.set('view engine')580      , root: this.set('views') || process.cwd() + '/views'581      , engines: engines582    });583584    // prime the cache585    if (opts.cache) cache[name] = view;586  }587588  // render589  try {590    view.render(opts, fn);591  } catch (err) {592    fn(err);593  }594};