Skip to content
Myr

application.js

This file

Path

lib/application.js

526 lines · 11.1 KiB · JavaScript

Last changed by

Merge branch 'master' of github.com:visionmedia/expressTj Holowaychukbefore adoption613bdc9

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 * 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');7677  // implicit middleware78  this.use(connect.query());79  this.use(middleware.init(this));8081  // app locals82  this.locals = function(obj){83    for (var key in obj) self.locals[key] = obj[key];84    return self;85  };8687  // response locals88  this.locals.use = function(fn){89    if (3 == fn.length) {90      self.viewCallbacks.push(fn);91    } else {92      self.viewCallbacks.push(function(req, res, done){93        fn(req, res);94        done();95      });96    }97    return this;98  };99100  // router101  this._router = new Router(this);102  this.routes = this._router.routes;103  this.__defineGetter__('router', function(){104    this._usedRouter = true;105    this._router.caseSensitive = this.enabled('case sensitive routing');106    this._router.strict = this.enabled('strict routing');107    return this._router.middleware;108  });109110  // default locals111  this.locals.settings = this.settings;112113  // default production configuration114  this.configure('production', function(){115    this.enable('view cache');116  });117};118119/**120 * Remove routes matching the given `path`.121 *122 * @param {Route} path123 * @return {Boolean}124 * @api public125 */126127app.remove = function(path){128  return this._router.lookup('all', path).remove();129};130131/**132 * Lookup routes defined with a path133 * equivalent to `path`.134 *135 * @param {Stirng} path136 * @return {Array}137 * @api public138 */139140app.lookup = function(path){141  return this._router.lookup('all', path);142};143144/**145 * Proxy `connect#use()` to apply settings to146 * mounted applications.147 *148 * @param {String|Function|Server} route149 * @param {Function|Server} fn150 * @return {app} for chaining151 * @api public152 */153154app.use = function(route, fn){155  var app, home, handle;156157  // default route to '/'158  if ('string' != typeof route) fn = route, route = '/';159160  // express app161  if (fn.handle && fn.set) app = fn;162163  // restore .app property on req and res164  if (app) {165    app.route = route;166    fn = function(req, res, next) {167      var orig = req.app;168      app.handle(req, res, function(err){169        req.app = res.app = orig;170        next(err);171      });172    };173  }174175  connect.proto.use.call(this, route, fn);176177  // mounted an app178  if (app) {179    app.parent = this;180    app.emit('mount', this);181  }182183  return this;184};185186/**187 * Register the given template engine callback `fn`188 * as `ext`. For example we may wish to map ".html"189 * files to ejs rather than using the ".ejs" extension.190 *191 *    app.engine('.html', require('ejs').render);192 *193 * or194 *195 *    app.engine('html', require('ejs').render);196 *197 * @param {String} ext198 * @param {Function} fn199 * @return {app} for chaining200 * @api public201 */202203app.engine = function(ext, fn){204  if ('.' != ext[0]) ext = '.' + ext;205  this.engines[ext] = fn;206  return this;207};208209/**210 * Map the given param placeholder `name`(s) to the given callback(s).211 *212 * Param mapping is used to provide pre-conditions to routes213 * which us normalized placeholders. This callback has the same214 * signature as regular middleware, for example below when ":userId"215 * is used this function will be invoked in an attempt to load the user.216 *217 *      app.param('userId', function(req, res, next, id){218 *        User.find(id, function(err, user){219 *          if (err) {220 *            next(err);221 *          } else if (user) {222 *            req.user = user;223 *            next();224 *          } else {225 *            next(new Error('failed to load user'));226 *          }227 *        });228 *      });229 *230 * Passing a single function allows you to map logic231 * to the values passed to `app.param()`, for example232 * this is useful to provide coercion support in a concise manner.233 *234 * The following example maps regular expressions to param values235 * ensuring that they match, otherwise passing control to the next236 * route:237 *238 *      app.param(function(name, regexp){239 *        if (regexp instanceof RegExp) {240 *          return function(req, res, next, val){241 *            var captures;242 *            if (captures = regexp.exec(String(val))) {243 *              req.params[name] = captures;244 *              next();245 *            } else {246 *              next('route');247 *            }248 *          }249 *        }250 *      });251 *252 * We can now use it as shown below, where "/commit/:commit" expects253 * that the value for ":commit" is at 5 or more digits. The capture254 * groups are then available as `req.params.commit` as we defined255 * in the function above.256 *257 *    app.param('commit', /^\d{5,}$/);258 *259 * For more of this useful functionality take a look260 * at [express-params](http://github.com/visionmedia/express-params).261 *262 * @param {String|Array|Function} name263 * @param {Function} fn264 * @return {app} for chaining265 * @api public266 */267268app.param = function(name, fn){269  var self = this270    , fns = [].slice.call(arguments, 1);271272  // array273  if (Array.isArray(name)) {274    name.forEach(function(name){275      fns.forEach(function(fn){276        self.param(name, fn);277      });278    });279  // param logic280  } else if ('function' == typeof name) {281    this._router.param(name);282  // single283  } else {284    if (':' == name[0]) name = name.substr(1);285    fns.forEach(function(fn){286      self._router.param(name, fn);287    });288  }289290  return this;291};292293/**294 * Assign `setting` to `val`, or return `setting`'s value.295 * Mounted servers inherit their parent server's settings.296 *297 * @param {String} setting298 * @param {String} val299 * @return {Server|Mixed} for chaining, or the setting value300 * @api public301 */302303app.set = function(setting, val){304  if (1 == arguments.length) {305    if (this.settings.hasOwnProperty(setting)) {306      return this.settings[setting];307    } else if (this.parent) {308      return this.parent.set(setting);309    }310  } else {311    this.settings[setting] = val;312    return this;313  }314};315316/**317 * Return the app's absolute pathname318 * based on the parent(s) that have319 * mounted it.320 *321 * @return {String}322 * @api private323 */324325app.path = function(){326  return this.parent327    ? this.parent.path() + this.route328    : '';329};330331/**332 * Check if `setting` is enabled.333 *334 * @param {String} setting335 * @return {Boolean}336 * @api public337 */338339app.enabled = function(setting){340  return !!this.set(setting);341};342343/**344 * Check if `setting` is disabled.345 *346 * @param {String} setting347 * @return {Boolean}348 * @api public349 */350351app.disabled = function(setting){352  return !this.set(setting);353};354355/**356 * Enable `setting`.357 *358 * @param {String} setting359 * @return {app} for chaining360 * @api public361 */362363app.enable = function(setting){364  return this.set(setting, true);365};366367/**368 * Disable `setting`.369 *370 * @param {String} setting371 * @return {app} for chaining372 * @api public373 */374375app.disable = function(setting){376  return this.set(setting, false);377};378379/**380 * Configure callback for zero or more envs,381 * when no env is specified that callback will382 * be invoked for all environments. Any combination383 * can be used multiple times, in any order desired.384 *385 * Examples:386 *387 *    app.configure(function(){388 *      // executed for all envs389 *    });390 *391 *    app.configure('stage', function(){392 *      // executed staging env393 *    });394 *395 *    app.configure('stage', 'production', function(){396 *      // executed for stage and production397 *    });398 *399 * @param {String} env...400 * @param {Function} fn401 * @return {app} for chaining402 * @api public403 */404405app.configure = function(env, fn){406  var envs = 'all'407    , args = [].slice.call(arguments);408  fn = args.pop();409  if (args.length) envs = args;410  if ('all' == envs || ~envs.indexOf(this.settings.env)) fn.call(this);411  return this;412};413414/**415 * Listen for connections.416 *417 * This method takes the same arguments418 * as node's `http.Server#listen()`.  419 *420 * @return {http.Server}421 * @api public422 */423424app.listen = function(){425  var server = http.createServer(this);426  return server.listen.apply(server, arguments);427};428429/**430 * Delegate `.VERB(...)` calls to `.route(VERB, ...)`.431 */432433methods.forEach(function(method){434  app[method] = function(path){435    if ('get' == method && 1 == arguments.length) return this.set(path); 436    var args = [method].concat([].slice.call(arguments));437    if (!this._usedRouter) this.use(this.router);438    return this._router.route.apply(this._router, args);439  }440});441442/**443 * Special-cased "all" method, applying the given route `path`,444 * middleware, and callback to _every_ HTTP method.445 *446 * @param {String} path447 * @param {Function} ...448 * @return {app} for chaining449 * @api public450 */451452app.all = function(path){453  var args = arguments;454  methods.forEach(function(method){455    if ('all' == method) return;456    app[method].apply(this, args);457  }, this);458  return this;459};460461// del -> delete alias462463app.del = app.delete;464465/**466 * Render the given view `name` name with `options`467 * and a callback accepting an error and the468 * rendered template string.469 *470 * @param {String} name471 * @param {String|Function} options or fn472 * @param {Function} fn473 * @api public474 */475476app.render = function(name, options, fn){477  var self = this478    , opts = {}479    , cache = this.cache480    , engines = this.engines481    , view;482483  // support callback function as second arg484  if ('function' == typeof options) {485    fn = options, options = {};486  }487488  // merge app.locals489  utils.merge(opts, this.locals);490491  // merge options.locals492  if (options.locals) {493    utils.merge(opts, options.locals);494    delete opts.locals;495  }496497  // merge options498  utils.merge(opts, options);499500  // set .cache unless explicitly provided501  opts.cache = null == opts.cache502    ? this.enabled('view cache')503    : opts.cache;504505  // primed cache506  if (opts.cache) view = cache[name];507508  // view509  if (!view) {510    view = new View(name, {511        defaultEngine: this.get('view engine')512      , root: this.get('views') || process.cwd() + '/views'513      , engines: engines514    });515516    // prime the cache517    if (opts.cache) cache[name] = view;518  }519520  // render521  try {522    view.render(opts, fn);523  } catch (err) {524    fn(err);525  }526};