Skip to content
Myr

application.js

This file

Path

lib/application.js

595 lines · 12.8 KiB · JavaScript

Last changed by

removed old view.jsTj Holowaychukbefore adoptioncecbaf2

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  , view = require('./view')15  , toArray = require('./utils').toArray16  , methods = Router.methods.concat('del', 'all')17  , res = require('./response')18  , union = require('./utils').union19  , url = require('url')20  , utils = connect.utils21  , path = require('path')22  , extname = path.extname23  , join = path.join24  , fs = require('fs')25  , qs = require('qs');2627/**28 * Expose `HTTPServer`.29 */3031var app = exports = module.exports = {};3233/**34 * Initialize the server.35 *36 * @param {Array} middleware37 * @api private38 */3940app.init = function(middleware){41  var self = this;42  this.settings = {};43  this.engines = {};44  this.redirects = {};45  this.isCallbacks = {};4647  this.set('home', '/');48  this.set('env', process.env.NODE_ENV || 'development');49  this.use(connect.query());5051  /**52   * Assign several locals with the given `obj`,53   * or return the locals.54   *55   * @param {Object} obj56   * @return {Object|HTTPServer}57   * @api public58   */5960  this.locals = function(obj){61    for (var key in obj) {62      self.locals[key] = obj[key];63    }64    return self;65  };6667  // expose objects to each other68  this.use(function(req, res, next){69    var charset;70    req.query = req.query || {};71    res.setHeader('X-Powered-By', 'Express');72    req.app = res.app = self;73    req.res = res;74    res.req = req;75    req.next = next;7677    // charset78    if (charset = self.set('charset')) res.charset = charset;7980    /**81     * Assign several locals with the given `obj`,82     * or return the locals.83     *84     * @param {Object} obj85     * @return {Object|ServerResponse}86     * @api public87     */8889    res.locals = function(obj){90      for (var key in obj) {91        res.locals[key] = obj[key];92      }93      return res;94    };9596    next();97  });9899  // apply middleware100  if (middleware) middleware.forEach(self.use.bind(self));101102  // router103  this.routes = new Router(this);104  this.__defineGetter__('router', function(){105    this.__usedRouter = true;106    return self.routes.middleware;107  });108109  // default locals110  this.locals.settings = this.settings;111112  // default development configuration113  this.configure('development', function(){114    this.enable('hints');115  });116117  // default production configuration118  this.configure('production', function(){119    this.enable('view cache');120  });121122  // route manipulation methods123  methods.forEach(function(method){124    self.lookup[method] = function(path){125      return self.routes.lookup(method, path);126    };127128    self.match[method] = function(path){129      return self.routes.match(method, path);130    };131132    self.remove[method] = function(path){133      return self.routes.lookup(method, path).remove();134    };135  });136137  // del -> delete138  self.lookup.del = self.lookup.delete;139  self.match.del = self.match.delete;140  self.remove.del = self.remove.delete;141};142143/**144 * Remove routes matching the given `path`.145 *146 * @param {Route} path147 * @return {Boolean}148 * @api public149 */150151app.remove = function(path){152  return this.routes.lookup('all', path).remove();153};154155/**156 * Lookup routes defined with a path157 * equivalent to `path`.158 *159 * @param {Stirng} path160 * @return {Array}161 * @api public162 */163164app.lookup = function(path){165  return this.routes.lookup('all', path);166};167168/**169 * Lookup routes matching the given `url`.170 *171 * @param {Stirng} url172 * @return {Array}173 * @api public174 */175176app.match = function(url){177  return this.routes.match('all', url);178};179180/**181 * Proxy `connect.HTTPServer#use()` to apply settings to182 * mounted applications.183 *184 * @param {String|Function|Server} route185 * @param {Function|Server} middleware186 * @return {Server} for chaining187 * @api public188 */189190app.use = function(route, middleware){191  var app, home, handle;192193  if ('string' != typeof route) {194    middleware = route, route = '/';195  }196197  // express app198  if (middleware.handle && middleware.set) app = middleware;199200  // restore .app property on req and res201  if (app) {202    app.route = route;203    middleware = function(req, res, next) {204      var orig = req.app;205      app.handle(req, res, function(err){206        req.app = res.app = orig;207        next(err);208      });209    };210  }211212  connect.proto.use.call(this, route, middleware);213214  // mounted an app, invoke the hook215  // and adjust some settings216  if (app) {217    base = this.set('basepath') || this.route;218    if ('/' == base) base = '';219    base = base + (app.set('basepath') || app.route);220    app.set('basepath', base);221    app.parent = this;222    if (app.__mounted) app.__mounted.call(app, this);223  }224225  return this;226};227228/**229 * Assign a callback `fn` which is called230 * when this `Server` is passed to `Server#use()`.231 *232 * Examples:233 *234 *    var app = express.createServer()235 *      , blog = express.createServer();236 *237 *    blog.mounted(function(parent){238 *      // parent is app239 *      // "this" is blog240 *    });241 *242 *    app.use(blog);243 *244 * @param {Function} fn245 * @return {Server} for chaining246 * @api public247 */248249app.mounted = function(fn){250  this.__mounted = fn;251  return this;252};253254/**255 * Register the given template engine callback `fn`256 * as `ext`. For example we may wish to map ".html"257 * files to ejs rather than using the ".ejs" extension.258 *259 *    app.register('.html', require('ejs').render);260 *261 * or262 *263 *    app.register('html', require('ejs').render);264 *265 * @param {String} ext266 * @param {Function} fn267 * @return {Server} for chaining268 * @api public269 */270271app.register = function(ext, fn){272  if ('.' != ext[0]) ext = '.' + ext;273  this.engines[ext] = fn;274  return this;275};276277/**278 * Map the given param placeholder `name`(s) to the given callback `fn`.279 * Register the given view helpers `obj`. This method280 * can be called several times to apply additional helpers.281 *282 * @param {Object} obj283 * @return {Server} for chaining284 * @api public285 */286287app.locals = function(obj){288  utils.merge(this._locals, obj);289  return this;290};291292/**293 * Map the given param placeholder `name`(s) to the given callback(s).294 *295 * Param mapping is used to provide pre-conditions to routes296 * which us normalized placeholders. This callback has the same297 * signature as regular middleware, for example below when ":userId"298 * is used this function will be invoked in an attempt to load the user.299 *300 *      app.param('userId', function(req, res, next, id){301 *        User.find(id, function(err, user){302 *          if (err) {303 *            next(err);304 *          } else if (user) {305 *            req.user = user;306 *            next();307 *          } else {308 *            next(new Error('failed to load user'));309 *          }310 *        });311 *      });312 *313 * Passing a single function allows you to map logic314 * to the values passed to `app.param()`, for example315 * this is useful to provide coercion support in a concise manner.316 *317 * The following example maps regular expressions to param values318 * ensuring that they match, otherwise passing control to the next319 * route:320 *321 *      app.param(function(name, regexp){322 *        if (regexp instanceof RegExp) {323 *          return function(req, res, next, val){324 *            var captures;325 *            if (captures = regexp.exec(String(val))) {326 *              req.params[name] = captures;327 *              next();328 *            } else {329 *              next('route');330 *            }331 *          }332 *        }333 *      });334 *335 * We can now use it as shown below, where "/commit/:commit" expects336 * that the value for ":commit" is at 5 or more digits. The capture337 * groups are then available as `req.params.commit` as we defined338 * in the function above.339 *340 *    app.param('commit', /^\d{5,}$/);341 *342 * For more of this useful functionality take a look343 * at [express-params](http://github.com/visionmedia/express-params).344 *345 * @param {String|Array|Function} name346 * @param {Function} fn347 * @return {Server} for chaining348 * @api public349 */350351app.param = function(name, fn){352  var self = this353    , fns = [].slice.call(arguments, 1);354355  // array356  if (Array.isArray(name)) {357    name.forEach(function(name){358      fns.forEach(function(fn){359        self.param(name, fn);360      });361    });362  // param logic363  } else if ('function' == typeof name) {364    this.routes.param(name);365  // single366  } else {367    if (':' == name[0]) name = name.substr(1);368    fns.forEach(function(fn){369      self.routes.param(name, fn);370    });371  }372373  return this;374};375376/**377 * Register the given callback `fn` for the given `type`.378 *379 * @param {String} type380 * @param {Function} fn381 * @return {Server} for chaining382 * @api public383 */384385app.is = function(type, fn){386  if (!fn) return this.isCallbacks[type];387  this.isCallbacks[type] = fn;388  return this;389};390391/**392 * Assign `setting` to `val`, or return `setting`'s value.393 * Mounted servers inherit their parent server's settings.394 *395 * @param {String} setting396 * @param {String} val397 * @return {Server|Mixed} for chaining, or the setting value398 * @api public399 */400401app.set = function(setting, val){402  if (val === undefined) {403    if (this.settings.hasOwnProperty(setting)) {404      return this.settings[setting];405    } else if (this.parent) {406      return this.parent.set(setting);407    }408  } else {409    this.settings[setting] = val;410    return this;411  }412};413414/**415 * Check if `setting` is enabled.416 *417 * @param {String} setting418 * @return {Boolean}419 * @api public420 */421422app.enabled = function(setting){423  return !!this.set(setting);424};425426/**427 * Check if `setting` is disabled.428 *429 * @param {String} setting430 * @return {Boolean}431 * @api public432 */433434app.disabled = function(setting){435  return !this.set(setting);436};437438/**439 * Enable `setting`.440 *441 * @param {String} setting442 * @return {Server} for chaining443 * @api public444 */445446app.enable = function(setting){447  return this.set(setting, true);448};449450/**451 * Disable `setting`.452 *453 * @param {String} setting454 * @return {Server} for chaining455 * @api public456 */457458app.disable = function(setting){459  return this.set(setting, false);460};461462/**463 * Redirect `key` to `url`.464 *465 * @param {String} key466 * @param {String} url467 * @return {Server} for chaining468 * @api public469 */470471app.redirect = function(key, url){472  this.redirects[key] = url;473  return this;474};475476/**477 * Configure callback for zero or more envs,478 * when no env is specified that callback will479 * be invoked for all environments. Any combination480 * can be used multiple times, in any order desired.481 *482 * Examples:483 *484 *    app.configure(function(){485 *      // executed for all envs486 *    });487 *488 *    app.configure('stage', function(){489 *      // executed staging env490 *    });491 *492 *    app.configure('stage', 'production', function(){493 *      // executed for stage and production494 *    });495 *496 * @param {String} env...497 * @param {Function} fn498 * @return {Server} for chaining499 * @api public500 */501502app.configure = function(env, fn){503  var envs = 'all'504    , args = toArray(arguments);505  fn = args.pop();506  if (args.length) envs = args;507  if ('all' == envs || ~envs.indexOf(this.settings.env)) fn.call(this);508  return this;509};510511/**512 * Delegate `.VERB(...)` calls to `.route(VERB, ...)`.513 */514515methods.forEach(function(method){516  app[method] = function(path){517    if (1 == arguments.length) return this.routes.lookup(method, path);518    var args = [method].concat(toArray(arguments));519    if (!this.__usedRouter) this.use(this.router);520    return this.routes._route.apply(this.routes, args);521  }522});523524/**525 * Special-cased "all" method, applying the given route `path`,526 * middleware, and callback to _every_ HTTP method.527 *528 * @param {String} path529 * @param {Function} ...530 * @return {Server} for chaining531 * @api public532 */533534app.all = function(path){535  var args = arguments;536  if (1 == args.length) return this.routes.lookup('all', path);537  methods.forEach(function(method){538    if ('all' == method) return;539    app[method].apply(this, args);540  }, this);541  return this;542};543544// del -> delete alias545546app.del = app.delete;547548/**549 * Render the given `view` name with `opts`550 * and a callback accepting an error and the551 * rendered template string.552 *553 * @param {String} view554 * @param {String|Function} opts or fn555 * @param {Function} fn556 * @api public557 */558559app.render = function(view, opts, fn){560  var self = this561    , options = {}562    , engines = this.engines563    , root = this.set('views') || process.cwd() + '/views';564565  // support callback function as second arg566  if ('function' == typeof opts) {567    fn = opts, opts = null;568  }569570  // merge app.locals571  union(options, this.locals);572573  // merge render() options574  if (opts) utils.merge(options, opts);575576  // join "view engine" if necessary577  var ext = extname(view);578  if (!ext) view += '.' + (ext = this.set('view engine'));579580  // pass .cache to the engine581  options.cache = this.enabled('view cache');582583  // when no extension nor "view engine" is given584  if (!ext) return fn(new Error('failed to find view "' + view + '"'));585586  // render587  try {588    var engine = engines[ext] = engines[ext] || require(ext);589    options.filename = join(root, view);590    view = fs.readFileSync(options.filename, 'utf8');591    engine.render(view, options, fn);592  } catch (err) {593    fn(err);594  }595};