Skip to content
Myr

application.js

This file

Path

lib/application.js

589 lines · 12.3 KiB · JavaScript

Last changed by

docsTj Holowaychukbefore adoption2e22887

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.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  // always parse req.query86  this.use(connect.query());8788  this.locals = function(obj){89    for (var key in obj) self.locals[key] = obj[key];90    return self;91  };9293  this.locals.use = function(fn){94    if (3 == fn.length) {95      self.viewCallbacks.push(fn);96    } else {97      self.viewCallbacks.push(function(req, res, done){98        fn(req, res);99        done();100      });101    }102    return this;103  };104105  // expose objects to each other106  this.use(function(req, res, next){107    var charset;108    res.setHeader('X-Powered-By', 'Express');109    req.app = res.app = self;110    req.res = res;111    res.req = req;112    req.next = next;113114    res.locals = function(obj){115      for (var key in obj) res.locals[key] = obj[key];116      return res;117    };118119    next();120  });121122  // router123  this._router = new Router(this);124  this.routes = this._router.routes;125  this.__defineGetter__('router', function(){126    this.__usedRouter = true;127    return self._router.middleware;128  });129130  // default locals131  this.locals.settings = this.settings;132133  // default production configuration134  this.configure('production', function(){135    this.enable('view cache');136  });137};138139/**140 * Remove routes matching the given `path`.141 *142 * @param {Route} path143 * @return {Boolean}144 * @api public145 */146147app.remove = function(path){148  return this._router.lookup('all', path).remove();149};150151/**152 * Lookup routes defined with a path153 * equivalent to `path`.154 *155 * @param {Stirng} path156 * @return {Array}157 * @api public158 */159160app.lookup = function(path){161  return this._router.lookup('all', path);162};163164/**165 * Lookup routes matching the given `url`.166 *167 * @param {Stirng} url168 * @return {Array}169 * @api public170 */171172app.match = function(url){173  return this._router.match('all', url);174};175176/**177 * Proxy `connect#use()` to apply settings to178 * mounted applications.179 *180 * @param {String|Function|Server} route181 * @param {Function|Server} middleware182 * @return {Server} for chaining183 * @api public184 */185186app.use = function(route, middleware){187  var app, home, handle;188189  if ('string' != typeof route) {190    middleware = route, route = '/';191  }192193  // express app194  if (middleware.handle && middleware.set) app = middleware;195196  // restore .app property on req and res197  if (app) {198    app.route = route;199    middleware = function(req, res, next) {200      var orig = req.app;201      app.handle(req, res, function(err){202        req.app = res.app = orig;203        next(err);204      });205    };206  }207208  connect.proto.use.call(this, route, middleware);209210  // mounted an app, invoke the hook211  // and adjust some settings212  if (app) {213    var root = this.get('root') || this.route;214    if ('/' == root) root = '';215    root = root + (app.get('root') || app.route);216    app.set('root', root);217    app.parent = this;218    if (app.__mounted) app.__mounted.call(app, this);219  }220221  return this;222};223224/**225 * Assign a callback `fn` which is called226 * when this `Server` is passed to `Server#use()`.227 *228 * Examples:229 *230 *    var app = express.createServer()231 *      , blog = express.createServer();232 *233 *    blog.mounted(function(parent){234 *      // parent is app235 *      // "this" is blog236 *    });237 *238 *    app.use(blog);239 *240 * @param {Function} fn241 * @return {Server} for chaining242 * @api public243 */244245app.mounted = function(fn){246  this.__mounted = fn;247  return this;248};249250/**251 * Register the given template engine callback `fn`252 * as `ext`. For example we may wish to map ".html"253 * files to ejs rather than using the ".ejs" extension.254 *255 *    app.register('.html', require('ejs').render);256 *257 * or258 *259 *    app.register('html', require('ejs').render);260 *261 * @param {String} ext262 * @param {Function} fn263 * @return {Server} for chaining264 * @api public265 */266267app.register = function(ext, fn){268  if ('.' != ext[0]) ext = '.' + ext;269  this.engines[ext] = fn;270  return this;271};272273/**274 * Map the given param placeholder `name`(s) to the given callback(s).275 *276 * Param mapping is used to provide pre-conditions to routes277 * which us normalized placeholders. This callback has the same278 * signature as regular middleware, for example below when ":userId"279 * is used this function will be invoked in an attempt to load the user.280 *281 *      app.param('userId', function(req, res, next, id){282 *        User.find(id, function(err, user){283 *          if (err) {284 *            next(err);285 *          } else if (user) {286 *            req.user = user;287 *            next();288 *          } else {289 *            next(new Error('failed to load user'));290 *          }291 *        });292 *      });293 *294 * Passing a single function allows you to map logic295 * to the values passed to `app.param()`, for example296 * this is useful to provide coercion support in a concise manner.297 *298 * The following example maps regular expressions to param values299 * ensuring that they match, otherwise passing control to the next300 * route:301 *302 *      app.param(function(name, regexp){303 *        if (regexp instanceof RegExp) {304 *          return function(req, res, next, val){305 *            var captures;306 *            if (captures = regexp.exec(String(val))) {307 *              req.params[name] = captures;308 *              next();309 *            } else {310 *              next('route');311 *            }312 *          }313 *        }314 *      });315 *316 * We can now use it as shown below, where "/commit/:commit" expects317 * that the value for ":commit" is at 5 or more digits. The capture318 * groups are then available as `req.params.commit` as we defined319 * in the function above.320 *321 *    app.param('commit', /^\d{5,}$/);322 *323 * For more of this useful functionality take a look324 * at [express-params](http://github.com/visionmedia/express-params).325 *326 * @param {String|Array|Function} name327 * @param {Function} fn328 * @return {Server} for chaining329 * @api public330 */331332app.param = function(name, fn){333  var self = this334    , fns = [].slice.call(arguments, 1);335336  // array337  if (Array.isArray(name)) {338    name.forEach(function(name){339      fns.forEach(function(fn){340        self.param(name, fn);341      });342    });343  // param logic344  } else if ('function' == typeof name) {345    this._router.param(name);346  // single347  } else {348    if (':' == name[0]) name = name.substr(1);349    fns.forEach(function(fn){350      self._router.param(name, fn);351    });352  }353354  return this;355};356357/**358 * Register the given callback `fn` for the given `type`.359 *360 * @param {String} type361 * @param {Function} fn362 * @return {Server} for chaining363 * @api public364 */365366app.is = function(type, fn){367  if (!fn) return this.isCallbacks[type];368  this.isCallbacks[type] = fn;369  return this;370};371372/**373 * Assign `setting` to `val`, or return `setting`'s value.374 * Mounted servers inherit their parent server's settings.375 *376 * @param {String} setting377 * @param {String} val378 * @return {Server|Mixed} for chaining, or the setting value379 * @api public380 */381382app.set = function(setting, val){383  if (val === undefined) {384    if (this.settings.hasOwnProperty(setting)) {385      return this.settings[setting];386    } else if (this.parent) {387      return this.parent.set(setting);388    }389  } else {390    this.settings[setting] = val;391    return this;392  }393};394395/**396 * Check if `setting` is enabled.397 *398 * @param {String} setting399 * @return {Boolean}400 * @api public401 */402403app.enabled = function(setting){404  return !!this.set(setting);405};406407/**408 * Check if `setting` is disabled.409 *410 * @param {String} setting411 * @return {Boolean}412 * @api public413 */414415app.disabled = function(setting){416  return !this.set(setting);417};418419/**420 * Enable `setting`.421 *422 * @param {String} setting423 * @return {Server} for chaining424 * @api public425 */426427app.enable = function(setting){428  return this.set(setting, true);429};430431/**432 * Disable `setting`.433 *434 * @param {String} setting435 * @return {Server} for chaining436 * @api public437 */438439app.disable = function(setting){440  return this.set(setting, false);441};442443/**444 * Redirect `key` to `url`.445 *446 * @param {String} key447 * @param {String} url448 * @return {Server} for chaining449 * @api public450 */451452app.redirect = function(key, url){453  this.redirects[key] = url;454  return this;455};456457/**458 * Configure callback for zero or more envs,459 * when no env is specified that callback will460 * be invoked for all environments. Any combination461 * can be used multiple times, in any order desired.462 *463 * Examples:464 *465 *    app.configure(function(){466 *      // executed for all envs467 *    });468 *469 *    app.configure('stage', function(){470 *      // executed staging env471 *    });472 *473 *    app.configure('stage', 'production', function(){474 *      // executed for stage and production475 *    });476 *477 * @param {String} env...478 * @param {Function} fn479 * @return {Server} for chaining480 * @api public481 */482483app.configure = function(env, fn){484  var envs = 'all'485    , args = toArray(arguments);486  fn = args.pop();487  if (args.length) envs = args;488  if ('all' == envs || ~envs.indexOf(this.settings.env)) fn.call(this);489  return this;490};491492/**493 * Delegate `.VERB(...)` calls to `.route(VERB, ...)`.494 */495496methods.forEach(function(method){497  app[method] = function(path){498    if ('get' == method && 1 == arguments.length) return this.set(path); 499    var args = [method].concat(toArray(arguments));500    if (!this.__usedRouter) this.use(this._router);501    return this._router._route.apply(this._router, args);502  }503});504505/**506 * Special-cased "all" method, applying the given route `path`,507 * middleware, and callback to _every_ HTTP method.508 *509 * @param {String} path510 * @param {Function} ...511 * @return {Server} for chaining512 * @api public513 */514515app.all = function(path){516  var args = arguments;517  methods.forEach(function(method){518    if ('all' == method) return;519    app[method].apply(this, args);520  }, this);521  return this;522};523524// del -> delete alias525526app.del = app.delete;527528/**529 * Render the given view `name` name with `options`530 * and a callback accepting an error and the531 * rendered template string.532 *533 * @param {String} name534 * @param {String|Function} options or fn535 * @param {Function} fn536 * @api public537 */538539app.render = function(name, options, fn){540  var self = this541    , opts = {}542    , cache = this.cache543    , engines = this.engines544    , view;545546  // support callback function as second arg547  if ('function' == typeof options) {548    fn = options, options = {};549  }550551  // merge app.locals552  utils.merge(opts, this.locals);553554  // merge options.locals555  if (options.locals) {556    utils.merge(opts, options.locals);557    delete opts.locals;558  }559560  // merge options561  utils.merge(opts, options);562563  // set .cache unless explicitly provided564  opts.cache = null == opts.cache565    ? this.enabled('view cache')566    : opts.cache;567568  // primed cache569  if (opts.cache) view = cache[name];570571  // view572  if (!view) {573    view = new View(name, {574        defaultEngine: this.set('view engine')575      , root: this.set('views') || process.cwd() + '/views'576      , engines: engines577    });578579    // prime the cache580    if (opts.cache) cache[name] = view;581  }582583  // render584  try {585    view.render(opts, fn);586  } catch (err) {587    fn(err);588  }589};