Skip to content
Myr

application.js

This file

Path

lib/application.js

529 lines · 11.2 KiB · JavaScript

Last changed by

ocdTJ Holowaychukbefore adoptiond115798

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  , debug = require('debug')('express:application')17  , View = require('./view')18  , url = require('url')19  , utils = connect.utils20  , path = require('path')21  , http = require('http')22  , join = path.join23  , fs = require('fs');2425/**26 * Application prototype.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.viewCallbacks = [];47  this.defaultConfiguration();4849  // route reflection methods50  methods.forEach(function(method){51    self.lookup[method] = function(path){52      return self._router.lookup(method, path);53    };5455    self.remove[method] = function(path){56      return self._router.lookup(method, path).remove();57    };58  });5960  // del -> delete61  self.lookup.del = self.lookup.delete;62  self.remove.del = self.remove.delete;63};6465/**66 * Initialize application configuration.67 *68 * @api private69 */7071app.defaultConfiguration = function(){72  var self = this;7374  // default settings75  this.set('env', process.env.NODE_ENV || 'development');76  debug('booting in %s mode', this.get('env'));7778  // implicit middleware79  this.use(connect.query());80  this.use(middleware.init(this));8182  // app locals83  this.locals = function(obj){84    for (var key in obj) self.locals[key] = obj[key];85    return self;86  };8788  // response locals89  this.locals.use = function(fn){90    if (3 == fn.length) {91      self.viewCallbacks.push(fn);92    } else {93      self.viewCallbacks.push(function(req, res, done){94        fn(req, res);95        done();96      });97    }98    return this;99  };100101  // router102  this._router = new Router(this);103  this.routes = this._router.routes;104  this.__defineGetter__('router', function(){105    this._usedRouter = true;106    this._router.caseSensitive = this.enabled('case sensitive routing');107    this._router.strict = this.enabled('strict routing');108    return this._router.middleware;109  });110111  // default locals112  this.locals.settings = this.settings;113114  // default configuration115  this.configure('development', function(){116    this.set('json spaces', 2);117  });118119  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 {String} path141 * @return {Array}142 * @api public143 */144145app.lookup = function(path){146  return this._router.lookup('all', path);147};148149/**150 * Proxy `connect#use()` to apply settings to151 * mounted applications.152 *153 * @param {String|Function|Server} route154 * @param {Function|Server} fn155 * @return {app} for chaining156 * @api public157 */158159app.use = function(route, fn){160  var app, home, handle;161162  // default route to '/'163  if ('string' != typeof route) fn = route, route = '/';164165  // express app166  if (fn.handle && fn.set) app = fn;167168  // restore .app property on req and res169  if (app) {170    app.route = route;171    fn = function(req, res, next) {172      var orig = req.app;173      app.handle(req, res, function(err){174        req.app = res.app = orig;175        next(err);176      });177    };178  }179180  debug('use %s %s', route, fn.name || 'unnamed');181  connect.proto.use.call(this, route, fn);182183  // mounted an app184  if (app) {185    app.parent = this;186    app.emit('mount', this);187  }188189  return this;190};191192/**193 * Register the given template engine callback `fn`194 * as `ext`. For example we may wish to map ".html"195 * files to ejs rather than using the ".ejs" extension.196 *197 *    app.engine('.html', require('ejs').render);198 *199 * or200 *201 *    app.engine('html', require('ejs').render);202 *203 * @param {String} ext204 * @param {Function} fn205 * @return {app} for chaining206 * @api public207 */208209app.engine = function(ext, fn){210  if ('.' != ext[0]) ext = '.' + ext;211  this.engines[ext] = fn;212  return this;213};214215/**216 * Map the given param placeholder `name`(s) to the given callback(s).217 *218 * Param mapping is used to provide pre-conditions to routes219 * which us normalized placeholders. This callback has the same220 * signature as regular middleware, for example below when ":userId"221 * is used this function will be invoked in an attempt to load the user.222 *223 *      app.param('userId', function(req, res, next, id){224 *        User.find(id, function(err, user){225 *          if (err) {226 *            next(err);227 *          } else if (user) {228 *            req.user = user;229 *            next();230 *          } else {231 *            next(new Error('failed to load user'));232 *          }233 *        });234 *      });235 *236 * Passing a single function allows you to map logic237 * to the values passed to `app.param()`, for example238 * this is useful to provide coercion support in a concise manner.239 *240 * The following example maps regular expressions to param values241 * ensuring that they match, otherwise passing control to the next242 * route:243 *244 *      app.param(function(name, regexp){245 *        if (regexp instanceof RegExp) {246 *          return function(req, res, next, val){247 *            var captures;248 *            if (captures = regexp.exec(String(val))) {249 *              req.params[name] = captures;250 *              next();251 *            } else {252 *              next('route');253 *            }254 *          }255 *        }256 *      });257 *258 * We can now use it as shown below, where "/commit/:commit" expects259 * that the value for ":commit" is at 5 or more digits. The capture260 * groups are then available as `req.params.commit` as we defined261 * in the function above.262 *263 *    app.param('commit', /^\d{5,}$/);264 *265 * For more of this useful functionality take a look266 * at [express-params](http://github.com/visionmedia/express-params).267 *268 * @param {String|Array|Function} name269 * @param {Function} fn270 * @return {app} for chaining271 * @api public272 */273274app.param = function(name, fn){275  var self = this276    , fns = [].slice.call(arguments, 1);277278  // array279  if (Array.isArray(name)) {280    name.forEach(function(name){281      fns.forEach(function(fn){282        self.param(name, fn);283      });284    });285  // param logic286  } else if ('function' == typeof name) {287    this._router.param(name);288  // single289  } else {290    if (':' == name[0]) name = name.substr(1);291    fns.forEach(function(fn){292      self._router.param(name, fn);293    });294  }295296  return this;297};298299/**300 * Assign `setting` to `val`, or return `setting`'s value.301 * Mounted servers inherit their parent server's settings.302 *303 * @param {String} setting304 * @param {String} val305 * @return {Server|Mixed} for chaining, or the setting value306 * @api public307 */308309app.set = function(setting, val){310  if (1 == arguments.length) {311    if (this.settings.hasOwnProperty(setting)) {312      return this.settings[setting];313    } else if (this.parent) {314      return this.parent.set(setting);315    }316  } else {317    this.settings[setting] = val;318    return this;319  }320};321322/**323 * Return the app's absolute pathname324 * based on the parent(s) that have325 * mounted it.326 *327 * @return {String}328 * @api private329 */330331app.path = function(){332  return this.parent333    ? this.parent.path() + this.route334    : '';335};336337/**338 * Check if `setting` is enabled.339 *340 * @param {String} setting341 * @return {Boolean}342 * @api public343 */344345app.enabled = function(setting){346  return !!this.set(setting);347};348349/**350 * Check if `setting` is disabled.351 *352 * @param {String} setting353 * @return {Boolean}354 * @api public355 */356357app.disabled = function(setting){358  return !this.set(setting);359};360361/**362 * Enable `setting`.363 *364 * @param {String} setting365 * @return {app} for chaining366 * @api public367 */368369app.enable = function(setting){370  return this.set(setting, true);371};372373/**374 * Disable `setting`.375 *376 * @param {String} setting377 * @return {app} for chaining378 * @api public379 */380381app.disable = function(setting){382  return this.set(setting, false);383};384385/**386 * Configure callback for zero or more envs,387 * when no env is specified that callback will388 * be invoked for all environments. Any combination389 * can be used multiple times, in any order desired.390 *391 * Examples:392 *393 *    app.configure(function(){394 *      // executed for all envs395 *    });396 *397 *    app.configure('stage', function(){398 *      // executed staging env399 *    });400 *401 *    app.configure('stage', 'production', function(){402 *      // executed for stage and production403 *    });404 *405 * @param {String} env...406 * @param {Function} fn407 * @return {app} for chaining408 * @api public409 */410411app.configure = function(env, fn){412  var envs = 'all'413    , args = [].slice.call(arguments);414  fn = args.pop();415  if (args.length) envs = args;416  if ('all' == envs || ~envs.indexOf(this.settings.env)) fn.call(this);417  return this;418};419420/**421 * Listen for connections.422 *423 * This method takes the same arguments424 * as node's `http.Server#listen()`.  425 *426 * @return {http.Server}427 * @api public428 */429430app.listen = function(){431  var server = http.createServer(this);432  return server.listen.apply(server, arguments);433};434435/**436 * Delegate `.VERB(...)` calls to `.route(VERB, ...)`.437 */438439methods.forEach(function(method){440  app[method] = function(path){441    if ('get' == method && 1 == arguments.length) return this.set(path); 442    var args = [method].concat([].slice.call(arguments));443    if (!this._usedRouter) this.use(this.router);444    return this._router.route.apply(this._router, args);445  }446});447448/**449 * Special-cased "all" method, applying the given route `path`,450 * middleware, and callback to _every_ HTTP method.451 *452 * @param {String} path453 * @param {Function} ...454 * @return {app} for chaining455 * @api public456 */457458app.all = function(path){459  var args = arguments;460  methods.forEach(function(method){461    if ('all' == method || 'del' == method) return;462    app[method].apply(this, args);463  }, this);464  return this;465};466467// del -> delete alias468469app.del = app.delete;470471/**472 * Render the given view `name` name with `options`473 * and a callback accepting an error and the474 * rendered template string.475 *476 * @param {String} name477 * @param {String|Function} options or fn478 * @param {Function} fn479 * @api public480 */481482app.render = function(name, options, fn){483  var self = this484    , opts = {}485    , cache = this.cache486    , engines = this.engines487    , view;488489  // support callback function as second arg490  if ('function' == typeof options) {491    fn = options, options = {};492  }493494  // merge app.locals495  utils.merge(opts, this.locals);496497  // merge options.locals498  if (options.locals) utils.merge(opts, options.locals);499500  // merge options501  utils.merge(opts, options);502503  // set .cache unless explicitly provided504  opts.cache = null == opts.cache505    ? this.enabled('view cache')506    : opts.cache;507508  // primed cache509  if (opts.cache) view = cache[name];510511  // view512  if (!view) {513    view = new View(name, {514        defaultEngine: this.get('view engine')515      , root: this.get('views') || process.cwd() + '/views'516      , engines: engines517    });518519    // prime the cache520    if (opts.cache) cache[name] = view;521  }522523  // render524  try {525    view.render(opts, fn);526  } catch (err) {527    fn(err);528  }529};