Skip to content
Myr

application.js

This file

Path

lib/application.js

592 lines · 12.4 KiB · JavaScript

Last changed by

Fixed res.clearCookie(), default path to "root" settingTj Holowaychukbefore adoption0f2f3d4

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    // charset115    if (charset = self.set('charset')) res.charset = charset;116117    res.locals = function(obj){118      for (var key in obj) res.locals[key] = obj[key];119      return res;120    };121122    next();123  });124125  // router126  this._router = new Router(this);127  this.routes = this._router.routes;128  this.__defineGetter__('router', function(){129    this.__usedRouter = true;130    return self._router.middleware;131  });132133  // default locals134  this.locals.settings = this.settings;135136  // default production configuration137  this.configure('production', function(){138    this.enable('view cache');139  });140};141142/**143 * Remove routes matching the given `path`.144 *145 * @param {Route} path146 * @return {Boolean}147 * @api public148 */149150app.remove = function(path){151  return this._router.lookup('all', path).remove();152};153154/**155 * Lookup routes defined with a path156 * equivalent to `path`.157 *158 * @param {Stirng} path159 * @return {Array}160 * @api public161 */162163app.lookup = function(path){164  return this._router.lookup('all', path);165};166167/**168 * Lookup routes matching the given `url`.169 *170 * @param {Stirng} url171 * @return {Array}172 * @api public173 */174175app.match = function(url){176  return this._router.match('all', url);177};178179/**180 * Proxy `connect.HTTPServer#use()` to apply settings to181 * mounted applications.182 *183 * @param {String|Function|Server} route184 * @param {Function|Server} middleware185 * @return {Server} for chaining186 * @api public187 */188189app.use = function(route, middleware){190  var app, home, handle;191192  if ('string' != typeof route) {193    middleware = route, route = '/';194  }195196  // express app197  if (middleware.handle && middleware.set) app = middleware;198199  // restore .app property on req and res200  if (app) {201    app.route = route;202    middleware = function(req, res, next) {203      var orig = req.app;204      app.handle(req, res, function(err){205        req.app = res.app = orig;206        next(err);207      });208    };209  }210211  connect.proto.use.call(this, route, middleware);212213  // mounted an app, invoke the hook214  // and adjust some settings215  if (app) {216    base = this.set('basepath') || this.route;217    if ('/' == base) base = '';218    base = base + (app.set('basepath') || app.route);219    app.set('basepath', base);220    app.parent = this;221    if (app.__mounted) app.__mounted.call(app, this);222  }223224  return this;225};226227/**228 * Assign a callback `fn` which is called229 * when this `Server` is passed to `Server#use()`.230 *231 * Examples:232 *233 *    var app = express.createServer()234 *      , blog = express.createServer();235 *236 *    blog.mounted(function(parent){237 *      // parent is app238 *      // "this" is blog239 *    });240 *241 *    app.use(blog);242 *243 * @param {Function} fn244 * @return {Server} for chaining245 * @api public246 */247248app.mounted = function(fn){249  this.__mounted = fn;250  return this;251};252253/**254 * Register the given template engine callback `fn`255 * as `ext`. For example we may wish to map ".html"256 * files to ejs rather than using the ".ejs" extension.257 *258 *    app.register('.html', require('ejs').render);259 *260 * or261 *262 *    app.register('html', require('ejs').render);263 *264 * @param {String} ext265 * @param {Function} fn266 * @return {Server} for chaining267 * @api public268 */269270app.register = function(ext, fn){271  if ('.' != ext[0]) ext = '.' + ext;272  this.engines[ext] = fn;273  return this;274};275276/**277 * Map the given param placeholder `name`(s) to the given callback(s).278 *279 * Param mapping is used to provide pre-conditions to routes280 * which us normalized placeholders. This callback has the same281 * signature as regular middleware, for example below when ":userId"282 * is used this function will be invoked in an attempt to load the user.283 *284 *      app.param('userId', function(req, res, next, id){285 *        User.find(id, function(err, user){286 *          if (err) {287 *            next(err);288 *          } else if (user) {289 *            req.user = user;290 *            next();291 *          } else {292 *            next(new Error('failed to load user'));293 *          }294 *        });295 *      });296 *297 * Passing a single function allows you to map logic298 * to the values passed to `app.param()`, for example299 * this is useful to provide coercion support in a concise manner.300 *301 * The following example maps regular expressions to param values302 * ensuring that they match, otherwise passing control to the next303 * route:304 *305 *      app.param(function(name, regexp){306 *        if (regexp instanceof RegExp) {307 *          return function(req, res, next, val){308 *            var captures;309 *            if (captures = regexp.exec(String(val))) {310 *              req.params[name] = captures;311 *              next();312 *            } else {313 *              next('route');314 *            }315 *          }316 *        }317 *      });318 *319 * We can now use it as shown below, where "/commit/:commit" expects320 * that the value for ":commit" is at 5 or more digits. The capture321 * groups are then available as `req.params.commit` as we defined322 * in the function above.323 *324 *    app.param('commit', /^\d{5,}$/);325 *326 * For more of this useful functionality take a look327 * at [express-params](http://github.com/visionmedia/express-params).328 *329 * @param {String|Array|Function} name330 * @param {Function} fn331 * @return {Server} for chaining332 * @api public333 */334335app.param = function(name, fn){336  var self = this337    , fns = [].slice.call(arguments, 1);338339  // array340  if (Array.isArray(name)) {341    name.forEach(function(name){342      fns.forEach(function(fn){343        self.param(name, fn);344      });345    });346  // param logic347  } else if ('function' == typeof name) {348    this._router.param(name);349  // single350  } else {351    if (':' == name[0]) name = name.substr(1);352    fns.forEach(function(fn){353      self._router.param(name, fn);354    });355  }356357  return this;358};359360/**361 * Register the given callback `fn` for the given `type`.362 *363 * @param {String} type364 * @param {Function} fn365 * @return {Server} for chaining366 * @api public367 */368369app.is = function(type, fn){370  if (!fn) return this.isCallbacks[type];371  this.isCallbacks[type] = fn;372  return this;373};374375/**376 * Assign `setting` to `val`, or return `setting`'s value.377 * Mounted servers inherit their parent server's settings.378 *379 * @param {String} setting380 * @param {String} val381 * @return {Server|Mixed} for chaining, or the setting value382 * @api public383 */384385app.set = function(setting, val){386  if (val === undefined) {387    if (this.settings.hasOwnProperty(setting)) {388      return this.settings[setting];389    } else if (this.parent) {390      return this.parent.set(setting);391    }392  } else {393    this.settings[setting] = val;394    return this;395  }396};397398/**399 * Check if `setting` is enabled.400 *401 * @param {String} setting402 * @return {Boolean}403 * @api public404 */405406app.enabled = function(setting){407  return !!this.set(setting);408};409410/**411 * Check if `setting` is disabled.412 *413 * @param {String} setting414 * @return {Boolean}415 * @api public416 */417418app.disabled = function(setting){419  return !this.set(setting);420};421422/**423 * Enable `setting`.424 *425 * @param {String} setting426 * @return {Server} for chaining427 * @api public428 */429430app.enable = function(setting){431  return this.set(setting, true);432};433434/**435 * Disable `setting`.436 *437 * @param {String} setting438 * @return {Server} for chaining439 * @api public440 */441442app.disable = function(setting){443  return this.set(setting, false);444};445446/**447 * Redirect `key` to `url`.448 *449 * @param {String} key450 * @param {String} url451 * @return {Server} for chaining452 * @api public453 */454455app.redirect = function(key, url){456  this.redirects[key] = url;457  return this;458};459460/**461 * Configure callback for zero or more envs,462 * when no env is specified that callback will463 * be invoked for all environments. Any combination464 * can be used multiple times, in any order desired.465 *466 * Examples:467 *468 *    app.configure(function(){469 *      // executed for all envs470 *    });471 *472 *    app.configure('stage', function(){473 *      // executed staging env474 *    });475 *476 *    app.configure('stage', 'production', function(){477 *      // executed for stage and production478 *    });479 *480 * @param {String} env...481 * @param {Function} fn482 * @return {Server} for chaining483 * @api public484 */485486app.configure = function(env, fn){487  var envs = 'all'488    , args = toArray(arguments);489  fn = args.pop();490  if (args.length) envs = args;491  if ('all' == envs || ~envs.indexOf(this.settings.env)) fn.call(this);492  return this;493};494495/**496 * Delegate `.VERB(...)` calls to `.route(VERB, ...)`.497 */498499methods.forEach(function(method){500  app[method] = function(path){501    if ('get' == method && 1 == arguments.length) return this.set(path); 502    var args = [method].concat(toArray(arguments));503    if (!this.__usedRouter) this.use(this._router);504    return this._router._route.apply(this._router, args);505  }506});507508/**509 * Special-cased "all" method, applying the given route `path`,510 * middleware, and callback to _every_ HTTP method.511 *512 * @param {String} path513 * @param {Function} ...514 * @return {Server} for chaining515 * @api public516 */517518app.all = function(path){519  var args = arguments;520  methods.forEach(function(method){521    if ('all' == method) return;522    app[method].apply(this, args);523  }, this);524  return this;525};526527// del -> delete alias528529app.del = app.delete;530531/**532 * Render the given view `name` name with `options`533 * and a callback accepting an error and the534 * rendered template string.535 *536 * @param {String} name537 * @param {String|Function} options or fn538 * @param {Function} fn539 * @api public540 */541542app.render = function(name, options, fn){543  var self = this544    , opts = {}545    , cache = this.cache546    , engines = this.engines547    , view;548549  // support callback function as second arg550  if ('function' == typeof options) {551    fn = options, options = {};552  }553554  // merge app.locals555  utils.merge(opts, this.locals);556557  // merge options.locals558  if (options.locals) {559    utils.merge(opts, options.locals);560    delete opts.locals;561  }562563  // merge options564  utils.merge(opts, options);565566  // set .cache unless explicitly provided567  opts.cache = null == opts.cache568    ? this.enabled('view cache')569    : opts.cache;570571  // primed cache572  if (opts.cache) view = cache[name];573574  // view575  if (!view) {576    view = new View(name, {577        defaultEngine: this.set('view engine')578      , root: this.set('views') || process.cwd() + '/views'579      , engines: engines580    });581582    // prime the cache583    if (opts.cache) cache[name] = view;584  }585586  // render587  try {588    view.render(opts, fn);589  } catch (err) {590    fn(err);591  }592};