Skip to content
Myr

http.js

This file

Path

lib/http.js

521 lines · 10.4 KiB · JavaScript

Last changed by

Added `app.local(name, val)`Tj Holowaychukbefore adoptiona4db994

History of this file

Take it

12/*!3 * Express - HTTPServer4 * Copyright(c) 2010 TJ Holowaychuk <tj@vision-media.ca>5 * MIT Licensed6 */78/**9 * Module dependencies.10 */1112var qs = require('qs')13  , connect = require('connect')14  , router = require('./router')15  , Router = require('./router')16  , view = require('./view')17  , toArray = require('./utils').toArray18  , methods = router.methods.concat('del', 'all')19  , res = require('./response')20  , url = require('url')21  , utils = connect.utils;2223/**24 * Expose `HTTPServer`.25 */2627exports = module.exports = HTTPServer;2829/**30 * Server proto.31 */3233var app = HTTPServer.prototype;3435/**36 * Initialize a new `HTTPServer` with optional `middleware`.37 *38 * @param {Array} middleware39 * @api public40 */4142function HTTPServer(middleware){43  connect.HTTPServer.call(this, []);44  this.init(middleware);45};4647/**48 * Inherit from `connect.HTTPServer`.49 */5051app.__proto__ = connect.HTTPServer.prototype;5253/**54 * Initialize the server.55 *56 * @param {Array} middleware57 * @api private58 */5960app.init = function(middleware){61  var self = this;62  this.cache = {};63  this.settings = {};64  this.redirects = {};65  this.isCallbacks = {};66  this._locals = {};67  this._dynamicLocals = {};6869  this.set('home', '/');70  this.set('env', process.env.NODE_ENV || 'development');7172  // expose objects to each other73  this.use(function(req, res, next){74    req.query = req.query || {};75    res.setHeader('X-Powered-By', 'Express');76    req.app = res.app = self;77    req.res = res;78    res.req = req;79    req.next = next;80    // assign req.query81    if (req.url.indexOf('?') > 0) {82      var query = url.parse(req.url).query;83      req.query = qs.parse(query);84    }85    next();86  });8788  // apply middleware89  if (middleware) middleware.forEach(self.use.bind(self));9091  // router92  this.routes = new Router(this);93  this.__defineGetter__('router', function(){94    this.__usedRouter = true;95    return self.routes.middleware;96  });9798  // default locals99  this.locals({100      settings: this.settings101    , app: this102  });103104  // default development configuration105  this.configure('development', function(){106    this.enable('hints');107  });108109  // default production configuration110  this.configure('production', function(){111    this.enable('view cache');112  });113114  // route manipulation methods115  methods.forEach(function(method){116    self.lookup[method] = function(path){117      return self.routes.lookup(method, path);118    };119120    self.match[method] = function(path){121      return self.routes.match(method, path);122    };123124    self.remove[method] = function(path){125      return self.routes.lookup(method, path).remove();126    };127  });128129  // del -> delete130  self.lookup.del = self.lookup.delete;131  self.match.del = self.match.delete;132  self.remove.del = self.remove.delete;133};134135/**136 * Remove routes matching the given `path`.137 *138 * @param {Route} path139 * @return {Boolean}140 * @api public141 */142143app.remove = function(path){144  return this.routes.lookup('all', path).remove();145};146147/**148 * Lookup routes defined with a path149 * equivalent to `path`.150 *151 * @param {Stirng} path152 * @return {Array}153 * @api public154 */155156app.lookup = function(path){157  return this.routes.lookup('all', path);158};159160/**161 * Lookup routes matching the given `url`.162 *163 * @param {Stirng} url164 * @return {Array}165 * @api public166 */167168app.match = function(url){169  return this.routes.match('all', url);170};171172/**173 * Proxy `connect.HTTPServer#use()` to apply settings to174 * mounted applications.175 *176 * @param {String|Function|Server} route177 * @param {Function|Server} middleware178 * @return {Server} for chaining179 * @api public180 */181182app.use = function(route, middleware){183  var app, home, handle;184185  if ('string' != typeof route) {186    middleware = route, route = '/';187  }188189  // express app190  if (middleware.handle && middleware.set) app = middleware;191192  // restore .app property on req and res193  if (app) {194    app.route = route;195    middleware = function(req, res, next) {196      var orig = req.app;197      app.handle(req, res, function(err){198        req.app = res.app = orig;199        next(err);200      });201    };202  }203204  connect.HTTPServer.prototype.use.call(this, route, middleware);205206  // mounted an app, invoke the hook207  // and adjust some settings208  if (app) {209    home = app.set('home');210    if ('/' == home) home = '';211    app.set('home', app.route + home);212    app.parent = this;213    if (app.__mounted) app.__mounted.call(app, this);214  }215216  return this;217};218219/**220 * Assign a callback `fn` which is called221 * when this `Server` is passed to `Server#use()`.222 *223 * Examples:224 *225 *    var app = express.createServer()226 *      , blog = express.createServer();227 *228 *    blog.mounted(function(parent){229 *      // parent is app230 *      // "this" is blog231 *    });232 *233 *    app.use(blog);234 *235 * @param {Function} fn236 * @return {Server} for chaining237 * @api public238 */239240app.mounted = function(fn){241  this.__mounted = fn;242  return this;243};244245/**246 * See: view.register.247 *248 * @return {Server} for chaining249 * @api public250 */251252app.register = function(){253  view.register.apply(this, arguments);254  return this;255};256257/**258 * Assign the view local variable `name` to `val` or return the259 * local previously assigned to `name`.260 *261 * @param {String} name262 * @param {Mixed} val263 * @return {Mixed} val264 * @api public265 */266267app.local = function(name, val){268  this._locals = this._locals || {};269  return undefined === val270    ? this._locals[name]271    : this._locals[name] = val;272};273274/**275 * Assign several locals with the given `obj`,276 * or return the locals.277 *278 * @param {Object} obj279 * @return {Object|HTTPServer}280 * @api public281 */282283app.locals = function(obj){284  if (0 == arguments.length) return this._locals;285  for (var key in obj) {286    this.local(key, obj[key]);287  }288  return this;289};290291/**292 * Register the given dynamic view helpers `obj`. This method293 * can be called several times to apply additional helpers.294 *295 * @param {Object} obj296 * @return {Server} for chaining297 * @api public298 */299300app.dynamicLocals = function(obj){301  utils.merge(this._dynamicLocals, obj);302  return this;303};304305/**306 * Map the given param placeholder `name`(s) to the given callback `fn`.307 *308 * Param mapping is used to provide pre-conditions to routes309 * which us normalized placeholders. This callback has the same310 * signature as regular middleware, for example below when ":userId"311 * is used this function will be invoked in an attempt to load the user.312 *313 *      app.param('userId', function(req, res, next, id){314 *        User.find(id, function(err, user){315 *          if (err) {316 *            next(err);317 *          } else if (user) {318 *            req.user = user;319 *            next();320 *          } else {321 *            next(new Error('failed to load user'));322 *          }323 *        });324 *      });325 *326 * @param {String|Array|Function} name327 * @param {Function} fn328 * @return {Server} for chaining329 * @api public330 */331332app.param = function(name, fn){333  // array334  if (Array.isArray(name)) {335    name.forEach(function(name){336      this.param(name, fn);337    }, this);338  // param logic339  } else if ('function' == typeof name) {340    this.routes.param(name);341  // single342  } else {343    if (':' == name[0]) name = name.substr(1);344    this.routes.param(name, fn);345  }346347  return this;348};349350/**351 * Register the given callback `fn` for the given `type`.352 *353 * @param {String} type354 * @param {Function} fn355 * @return {Server} for chaining356 * @api public357 */358359app.is = function(type, fn){360  if (!fn) return this.isCallbacks[type];361  this.isCallbacks[type] = fn;362  return this;363};364365/**366 * Assign `setting` to `val`, or return `setting`'s value.367 * Mounted servers inherit their parent server's settings.368 *369 * @param {String} setting370 * @param {String} val371 * @return {Server|Mixed} for chaining, or the setting value372 * @api public373 */374375app.set = function(setting, val){376  if (val === undefined) {377    if (this.settings.hasOwnProperty(setting)) {378      return this.settings[setting];379    } else if (this.parent) {380      return this.parent.set(setting);381    }382  } else {383    this.settings[setting] = val;384    return this;385  }386};387388/**389 * Check if `setting` is enabled.390 *391 * @param {String} setting392 * @return {Boolean}393 * @api public394 */395396app.enabled = function(setting){397  return !!this.set(setting);398};399400/**401 * Check if `setting` is disabled.402 *403 * @param {String} setting404 * @return {Boolean}405 * @api public406 */407408app.disabled = function(setting){409  return !this.set(setting);410};411412/**413 * Enable `setting`.414 *415 * @param {String} setting416 * @return {Server} for chaining417 * @api public418 */419420app.enable = function(setting){421  return this.set(setting, true);422};423424/**425 * Disable `setting`.426 *427 * @param {String} setting428 * @return {Server} for chaining429 * @api public430 */431432app.disable = function(setting){433  return this.set(setting, false);434};435436/**437 * Redirect `key` to `url`.438 *439 * @param {String} key440 * @param {String} url441 * @return {Server} for chaining442 * @api public443 */444445app.redirect = function(key, url){446  this.redirects[key] = url;447  return this;448};449450/**451 * Configure callback for zero or more envs,452 * when no env is specified that callback will453 * be invoked for all environments. Any combination454 * can be used multiple times, in any order desired.455 *456 * Examples:457 *458 *    app.configure(function(){459 *      // executed for all envs460 *    });461 *462 *    app.configure('stage', function(){463 *      // executed staging env464 *    });465 *466 *    app.configure('stage', 'production', function(){467 *      // executed for stage and production468 *    });469 *470 * @param {String} env...471 * @param {Function} fn472 * @return {Server} for chaining473 * @api public474 */475476app.configure = function(env, fn){477  var envs = 'all'478    , args = toArray(arguments);479  fn = args.pop();480  if (args.length) envs = args;481  if ('all' == envs || ~envs.indexOf(this.settings.env)) fn.call(this);482  return this;483};484485/**486 * Delegate `.VERB(...)` calls to `.route(VERB, ...)`.487 */488489methods.forEach(function(method){490  app[method] = function(path){491    if (1 == arguments.length) return this.routes.lookup(method, path);492    var args = [method].concat(toArray(arguments));493    if (!this.__usedRouter) this.use(this.router);494    return this.routes._route.apply(this.routes, args);495  }496});497498/**499 * Special-cased "all" method, applying the given route `path`,500 * middleware, and callback to _every_ HTTP method.501 *502 * @param {String} path503 * @param {Function} ...504 * @return {Server} for chaining505 * @api public506 */507508app.all = function(path){509  var args = arguments;510  if (1 == args.length) return this.routes.lookup('all', path);511  methods.forEach(function(method){512    if ('all' == method) return;513    app[method].apply(this, args);514  }, this);515  return this;516};517518// del -> delete alias519520app.del = app.delete;521