Skip to content
Myr

http.js

This file

Path

lib/http.js

467 lines · 10.0 KiB · JavaScript

Last changed by

Added 'settings' local variable, containing the app's settingsTj Holowaychukbefore adoption9d2bd29

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 = connect.router15  , methods = router.methods.concat(['del', 'all'])16  , view = require('./view')17  , url = require('url')18  , utils = connect.utils;1920/**21 * Initialize a new `HTTPServer` with optional `middleware`.22 *23 * @param {Array} middleware24 * @api public25 */2627var Server = exports = module.exports = function HTTPServer(middleware){28  connect.HTTPServer.call(this, []);29  this.init(middleware);30};3132/**33 * Inherit from `connect.HTTPServer`.34 */3536Server.prototype.__proto__ = connect.HTTPServer.prototype;3738/**39 * Initialize the server.40 *41 * @param {Array} middleware42 * @api private43 */4445Server.prototype.init = function(middleware){46  var self = this;47  this.settings = {};48  this.redirects = {};49  this.isCallbacks = {};50  this.viewHelpers = {};51  this.dynamicViewHelpers = {};52  this.errorHandlers = [];5354  // default "home" to /55  this.set('home', '/');5657  // set "env" to NODE_ENV, defaulting to "development"58  this.set('env', process.env.NODE_ENV || 'development');5960  // expose objects to each other61  this.use(function(req, res, next){62    req.query = req.query || {};63    res.setHeader('X-Powered-By', 'Express');64    req.app = res.app = self;65    req.res = res;66    res.req = req;67    req.next = next;68    // assign req.query69    if (req.url.indexOf('?') > 0) {70      var query = url.parse(req.url).query;71      req.query = qs.parse(query);72    }73    next();74  });7576  // apply middleware77  if (middleware) middleware.forEach(self.use.bind(self));7879  // use router, expose as app.get(), etc80  var fn = router(function(app){ self.routes = app; });81  this.__defineGetter__('router', function(){82    this.__usedRouter = true;83    return fn;84  });8586  // default locals87  this.locals({ settings: this.settings });8889  // default development configuration90  this.configure('development', function(){91    this.enable('hints');92  });9394  // default production configuration95  this.configure('production', function(){96    this.enable('cache views');97  });9899  // register error handlers on "listening"100  // so that they disregard definition position.101  this.on('listening', this.registerErrorHandlers.bind(this));102};103104/**105 * When using the vhost() middleware register error handlers.106 */107108Server.prototype.onvhost = function(){109  this.registerErrorHandlers();110};111112/**113 * Register error handlers.114 *115 * @return {Server} for chaining116 * @api public117 */118119Server.prototype.registerErrorHandlers = function(){120  this.errorHandlers.forEach(function(fn){121    this.use(function(err, req, res, next){122      fn.apply(this, arguments);123    });124  }, this);125  return this;126};127128/**129 * Proxy `connect.HTTPServer#use()` to apply settings to130 * mounted applications.131 *132 * @param {String|Function|Server} route133 * @param {Function|Server} middleware134 * @return {Server} for chaining135 * @api public136 */137138Server.prototype.use = function(route, middleware){139  var app, home, handle;140141  if ('string' != typeof route) {142    middleware = route, route = '/';143  }144145  // express app146  if (middleware.handle && middleware.set) app = middleware;147148  // restore .app property on req and res149  if (app) {150    app.route = route;151    middleware = function(req, res, next) {152      var orig = req.app;153      app.handle(req, res, function(err){154        req.app = res.app = orig;155        next(err);156      });157    };158  }159160  connect.HTTPServer.prototype.use.call(this, route, middleware);161162  // mounted an app, invoke the hook163  // and adjust some settings164  if (app) {165    home = app.set('home');166    if ('/' == home) home = '';167    app.set('home', app.route + home);168    app.parent = this;169    if (app.__mounted) app.__mounted.call(app, this);170  }171172  return this;173};174175/**176 * Assign a callback `fn` which is called177 * when this `Server` is passed to `Server#use()`.178 *179 * Examples:180 *181 *    var app = express.createServer()182 *      , blog = express.createServer();183 *184 *    blog.mounted(function(parent){185 *      // parent is app186 *      // "this" is blog187 *    });188 *189 *    app.use(blog);190 *191 * @param {Function} fn192 * @return {Server} for chaining193 * @api public194 */195196Server.prototype.mounted = function(fn){197  this.__mounted = fn;198  return this;199};200201/**202 * See: view.register.203 *204 * @return {Server} for chaining205 * @api public206 */207208Server.prototype.register = function(){209  view.register.apply(this, arguments);210  return this;211};212213/**214 * Register the given view helpers `obj`. This method215 * can be called several times to apply additional helpers.216 *217 * @param {Object} obj218 * @return {Server} for chaining219 * @api public220 */221222Server.prototype.helpers =223Server.prototype.locals = function(obj){224  utils.merge(this.viewHelpers, obj);225  return this;226};227228/**229 * Register the given dynamic view helpers `obj`. This method230 * can be called several times to apply additional helpers.231 *232 * @param {Object} obj233 * @return {Server} for chaining234 * @api public235 */236237Server.prototype.dynamicHelpers = function(obj){238  utils.merge(this.dynamicViewHelpers, obj);239  return this;240};241242/**243 * Map the given param placeholder `name`(s) to the given callback `fn`.244 *245 * Param mapping is used to provide pre-conditions to routes246 * which us normalized placeholders. For example ":user_id" may247 * attempt to load the user from the database, where as ":num" may248 * pass the value through `parseInt(num, 10)`.249 *250 * When the callback function accepts only a single argument, the251 * value of placeholder is passed:252 *253 *    app.param('page', function(n){ return parseInt(n, 10); });254 *255 * After which "/users/:page" would automatically provide us with256 * an integer for `req.params.page`. If desired we could use the callback257 * signature shown below, and immediately `next(new Error('invalid page'))`258 * when `parseInt` fails.259 *260 * Alternatively the callback may accept the request, response, next, and261 * the value, acting like middlware:262 *263 *     app.param('userId', function(req, res, next, id){264 *       User.find(id, function(err, user){265 *         if (err) {266 *           next(err);267 *         } else if (user) {268 *           req.user = user;269 *           next();270 *         } else {271 *           next(new Error('failed to load user'));272 *         }273 *       });274 *     });275 *276 * Now every time ":userId" is present, the associated user object277 * will be loaded and assigned before the route handler is invoked.278 *279 * @param {String|Array} name280 * @param {Function} fn281 * @return {Server} for chaining282 * @api public283 */284285Server.prototype.param = function(name, fn){286  if (Array.isArray(name)) {287    name.forEach(function(name){288      this.param(name, fn);289    }, this);290  } else {291    if (':' == name[0]) name = name.substr(1);292    this.routes.param(name, fn);293  }294  return this;295};296297/**298 * Assign a custom exception handler callback `fn`.299 * These handlers are always _last_ in the middleware stack.300 *301 * @param {Function} fn302 * @return {Server} for chaining303 * @api public304 */305306Server.prototype.error = function(fn){307  this.errorHandlers.push(fn);308  return this;309};310311/**312 * Register the given callback `fn` for the given `type`.313 *314 * @param {String} type315 * @param {Function} fn316 * @return {Server} for chaining317 * @api public318 */319320Server.prototype.is = function(type, fn){321  if (!fn) return this.isCallbacks[type];322  this.isCallbacks[type] = fn;323  return this;324};325326/**327 * Assign `setting` to `val`, or return `setting`'s value.328 * Mounted servers inherit their parent server's settings.329 *330 * @param {String} setting331 * @param {String} val332 * @return {Server|Mixed} for chaining, or the setting value333 * @api public334 */335336Server.prototype.set = function(setting, val){337  if (val === undefined) {338    if (this.settings.hasOwnProperty(setting)) {339      return this.settings[setting];340    } else if (this.parent) {341      return this.parent.set(setting);342    }343  } else {344    this.settings[setting] = val;345    return this;346  }347};348349/**350 * Check if `setting` is enabled.351 *352 * @param {String} setting353 * @return {Boolean}354 * @api public355 */356357Server.prototype.enabled = function(setting){358  return !!this.set(setting);359};360361/**362 * Check if `setting` is disabled.363 *364 * @param {String} setting365 * @return {Boolean}366 * @api public367 */368369Server.prototype.disabled = function(setting){370  return !this.set(setting);371};372373/**374 * Enable `setting`.375 *376 * @param {String} setting377 * @return {Server} for chaining378 * @api public379 */380381Server.prototype.enable = function(setting){382  return this.set(setting, true);383};384385/**386 * Disable `setting`.387 *388 * @param {String} setting389 * @return {Server} for chaining390 * @api public391 */392393Server.prototype.disable = function(setting){394  return this.set(setting, false);395};396397/**398 * Redirect `key` to `url`.399 *400 * @param {String} key401 * @param {String} url402 * @return {Server} for chaining403 * @api public404 */405406Server.prototype.redirect = function(key, url){407  this.redirects[key] = url;408  return this;409};410411/**412 * Configure callback for the given `env`.413 *414 * @param {String} env415 * @param {Function} fn416 * @return {Server} for chaining417 * @api public418 */419420Server.prototype.configure = function(env, fn){421  if ('function' == typeof env) {422    fn = env, env = 'all';423  }424  if ('all' == env || env == this.settings.env) {425    fn.call(this);426  }427  return this;428};429430// Generate routing methods431432function generateMethod(method){433  Server.prototype[method] = function(path, fn){434    var self = this;435436    // Ensure router is mounted437    if (!this.__usedRouter) {438      this.use(this.router);439    }440441    // Route specific middleware support442    if (arguments.length > 2) {443      var args = Array.prototype.slice.call(arguments, 1);444      fn = args.pop();445      (function stack(middleware){446        middleware.forEach(function(fn){447          if (Array.isArray(fn)) {448            stack(fn);449          } else {450            self[method](path, fn);451          }452        });453      })(args);454    }455456    // Generate the route457    this.routes[method](path, fn);458    return this;459  };460  return arguments.callee;461}462463methods.forEach(generateMethod);464465// Alias delete as "del"466467Server.prototype.del = Server.prototype.delete;