Skip to content
Myr

application.js

This file

Path

lib/application.js

529 lines · 11.1 KiB · JavaScript

Last changed by

Added "json replacer" and "json spaces" settings. Closes #996 [credit to jed]TJ Holowaychukbefore adoptionff92afa

History of this file

Take it

1/*!2 * Express - proto3 * Copyright(c) 2010 TJ Holowaychuk <tj@vision-media.ca>4 * MIT Licensed5 */67/**8 * Module dependencies.9 */1011var connect = require('connect')12  , Router = require('./router')13  , methods = Router.methods.concat('del', 'all')14  , middleware = require('./middleware')15  , View = require('./view')16  , url = require('url')17  , utils = connect.utils18  , path = require('path')19  , http = require('http')20  , join = path.join21  , fs = require('fs')22  , qs = require('qs');2324/**25 * Application prototype.26 */2728var app = exports = module.exports = {};2930/**31 * Initialize the server.32 *33 *   - setup default configuration34 *   - setup default middleware35 *   - setup route reflection methods36 *37 * @api private38 */3940app.init = function(){41  var self = this;42  this.cache = {};43  this.settings = {};44  this.engines = {};45  this.viewCallbacks = [];46  this.defaultConfiguration();4748  // route reflection methods49  methods.forEach(function(method){50    self.lookup[method] = function(path){51      return self._router.lookup(method, path);52    };5354    self.remove[method] = function(path){55      return self._router.lookup(method, path).remove();56    };57  });5859  // del -> delete60  self.lookup.del = self.lookup.delete;61  self.remove.del = self.remove.delete;62};6364/**65 * Initialize application configuration.66 *67 * @api private68 */6970app.defaultConfiguration = function(){71  var self = this;7273  // default settings74  this.set('env', process.env.NODE_ENV || 'development');7576  // implicit middleware77  this.use(connect.query());78  this.use(middleware.init(this));7980  // app locals81  this.locals = function(obj){82    for (var key in obj) self.locals[key] = obj[key];83    return self;84  };8586  // response locals87  this.locals.use = function(fn){88    if (3 == fn.length) {89      self.viewCallbacks.push(fn);90    } else {91      self.viewCallbacks.push(function(req, res, done){92        fn(req, res);93        done();94      });95    }96    return this;97  };9899  // router100  this._router = new Router(this);101  this.routes = this._router.routes;102  this.__defineGetter__('router', function(){103    this._usedRouter = true;104    this._router.caseSensitive = this.enabled('case sensitive routing');105    this._router.strict = this.enabled('strict routing');106    return this._router.middleware;107  });108109  // default locals110  this.locals.settings = this.settings;111112  // default configuration113  this.configure('development', function(){114    this.set('json spaces', 2);115  });116117  this.configure('production', function(){118    this.enable('view cache');119  });120};121122/**123 * Remove routes matching the given `path`.124 *125 * @param {Route} path126 * @return {Boolean}127 * @api public128 */129130app.remove = function(path){131  return this._router.lookup('all', path).remove();132};133134/**135 * Lookup routes defined with a path136 * equivalent to `path`.137 *138 * @param {String} path139 * @return {Array}140 * @api public141 */142143app.lookup = function(path){144  return this._router.lookup('all', path);145};146147/**148 * Proxy `connect#use()` to apply settings to149 * mounted applications.150 *151 * @param {String|Function|Server} route152 * @param {Function|Server} fn153 * @return {app} for chaining154 * @api public155 */156157app.use = function(route, fn){158  var app, home, handle;159160  // default route to '/'161  if ('string' != typeof route) fn = route, route = '/';162163  // express app164  if (fn.handle && fn.set) app = fn;165166  // restore .app property on req and res167  if (app) {168    app.route = route;169    fn = function(req, res, next) {170      var orig = req.app;171      app.handle(req, res, function(err){172        req.app = res.app = orig;173        next(err);174      });175    };176  }177178  connect.proto.use.call(this, route, fn);179180  // mounted an app181  if (app) {182    app.parent = this;183    app.emit('mount', this);184  }185186  return this;187};188189/**190 * Register the given template engine callback `fn`191 * as `ext`. For example we may wish to map ".html"192 * files to ejs rather than using the ".ejs" extension.193 *194 *    app.engine('.html', require('ejs').render);195 *196 * or197 *198 *    app.engine('html', require('ejs').render);199 *200 * @param {String} ext201 * @param {Function} fn202 * @return {app} for chaining203 * @api public204 */205206app.engine = function(ext, fn){207  if ('.' != ext[0]) ext = '.' + ext;208  this.engines[ext] = fn;209  return this;210};211212/**213 * Map the given param placeholder `name`(s) to the given callback(s).214 *215 * Param mapping is used to provide pre-conditions to routes216 * which us normalized placeholders. This callback has the same217 * signature as regular middleware, for example below when ":userId"218 * is used this function will be invoked in an attempt to load the user.219 *220 *      app.param('userId', function(req, res, next, id){221 *        User.find(id, function(err, user){222 *          if (err) {223 *            next(err);224 *          } else if (user) {225 *            req.user = user;226 *            next();227 *          } else {228 *            next(new Error('failed to load user'));229 *          }230 *        });231 *      });232 *233 * Passing a single function allows you to map logic234 * to the values passed to `app.param()`, for example235 * this is useful to provide coercion support in a concise manner.236 *237 * The following example maps regular expressions to param values238 * ensuring that they match, otherwise passing control to the next239 * route:240 *241 *      app.param(function(name, regexp){242 *        if (regexp instanceof RegExp) {243 *          return function(req, res, next, val){244 *            var captures;245 *            if (captures = regexp.exec(String(val))) {246 *              req.params[name] = captures;247 *              next();248 *            } else {249 *              next('route');250 *            }251 *          }252 *        }253 *      });254 *255 * We can now use it as shown below, where "/commit/:commit" expects256 * that the value for ":commit" is at 5 or more digits. The capture257 * groups are then available as `req.params.commit` as we defined258 * in the function above.259 *260 *    app.param('commit', /^\d{5,}$/);261 *262 * For more of this useful functionality take a look263 * at [express-params](http://github.com/visionmedia/express-params).264 *265 * @param {String|Array|Function} name266 * @param {Function} fn267 * @return {app} for chaining268 * @api public269 */270271app.param = function(name, fn){272  var self = this273    , fns = [].slice.call(arguments, 1);274275  // array276  if (Array.isArray(name)) {277    name.forEach(function(name){278      fns.forEach(function(fn){279        self.param(name, fn);280      });281    });282  // param logic283  } else if ('function' == typeof name) {284    this._router.param(name);285  // single286  } else {287    if (':' == name[0]) name = name.substr(1);288    fns.forEach(function(fn){289      self._router.param(name, fn);290    });291  }292293  return this;294};295296/**297 * Assign `setting` to `val`, or return `setting`'s value.298 * Mounted servers inherit their parent server's settings.299 *300 * @param {String} setting301 * @param {String} val302 * @return {Server|Mixed} for chaining, or the setting value303 * @api public304 */305306app.set = function(setting, val){307  if (1 == arguments.length) {308    if (this.settings.hasOwnProperty(setting)) {309      return this.settings[setting];310    } else if (this.parent) {311      return this.parent.set(setting);312    }313  } else {314    this.settings[setting] = val;315    return this;316  }317};318319/**320 * Return the app's absolute pathname321 * based on the parent(s) that have322 * mounted it.323 *324 * @return {String}325 * @api private326 */327328app.path = function(){329  return this.parent330    ? this.parent.path() + this.route331    : '';332};333334/**335 * Check if `setting` is enabled.336 *337 * @param {String} setting338 * @return {Boolean}339 * @api public340 */341342app.enabled = function(setting){343  return !!this.set(setting);344};345346/**347 * Check if `setting` is disabled.348 *349 * @param {String} setting350 * @return {Boolean}351 * @api public352 */353354app.disabled = function(setting){355  return !this.set(setting);356};357358/**359 * Enable `setting`.360 *361 * @param {String} setting362 * @return {app} for chaining363 * @api public364 */365366app.enable = function(setting){367  return this.set(setting, true);368};369370/**371 * Disable `setting`.372 *373 * @param {String} setting374 * @return {app} for chaining375 * @api public376 */377378app.disable = function(setting){379  return this.set(setting, false);380};381382/**383 * Configure callback for zero or more envs,384 * when no env is specified that callback will385 * be invoked for all environments. Any combination386 * can be used multiple times, in any order desired.387 *388 * Examples:389 *390 *    app.configure(function(){391 *      // executed for all envs392 *    });393 *394 *    app.configure('stage', function(){395 *      // executed staging env396 *    });397 *398 *    app.configure('stage', 'production', function(){399 *      // executed for stage and production400 *    });401 *402 * @param {String} env...403 * @param {Function} fn404 * @return {app} for chaining405 * @api public406 */407408app.configure = function(env, fn){409  var envs = 'all'410    , args = [].slice.call(arguments);411  fn = args.pop();412  if (args.length) envs = args;413  if ('all' == envs || ~envs.indexOf(this.settings.env)) fn.call(this);414  return this;415};416417/**418 * Listen for connections.419 *420 * This method takes the same arguments421 * as node's `http.Server#listen()`.  422 *423 * @return {http.Server}424 * @api public425 */426427app.listen = function(){428  var server = http.createServer(this);429  return server.listen.apply(server, arguments);430};431432/**433 * Delegate `.VERB(...)` calls to `.route(VERB, ...)`.434 */435436methods.forEach(function(method){437  app[method] = function(path){438    if ('get' == method && 1 == arguments.length) return this.set(path); 439    var args = [method].concat([].slice.call(arguments));440    if (!this._usedRouter) this.use(this.router);441    return this._router.route.apply(this._router, args);442  }443});444445/**446 * Special-cased "all" method, applying the given route `path`,447 * middleware, and callback to _every_ HTTP method.448 *449 * @param {String} path450 * @param {Function} ...451 * @return {app} for chaining452 * @api public453 */454455app.all = function(path){456  var args = arguments;457  methods.forEach(function(method){458    if ('all' == method || 'del' == method) return;459    app[method].apply(this, args);460  }, this);461  return this;462};463464// del -> delete alias465466app.del = app.delete;467468/**469 * Render the given view `name` name with `options`470 * and a callback accepting an error and the471 * rendered template string.472 *473 * @param {String} name474 * @param {String|Function} options or fn475 * @param {Function} fn476 * @api public477 */478479app.render = function(name, options, fn){480  var self = this481    , opts = {}482    , cache = this.cache483    , engines = this.engines484    , view;485486  // support callback function as second arg487  if ('function' == typeof options) {488    fn = options, options = {};489  }490491  // merge app.locals492  utils.merge(opts, this.locals);493494  // merge options.locals495  if (options.locals) {496    utils.merge(opts, options.locals);497    delete opts.locals;498  }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};