Skip to content
Myr

http.js

This file

Path

lib/http.js

453 lines · 9.6 KiB · JavaScript

Last changed by

Added view resolution hints when in developmentTj Holowaychukbefore adoptionf1f1261

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 development configuration87  this.configure('development', function(){88    this.enable('hints');89  });9091  // default production configuration92  this.configure('production', function(){93    this.enable('cache views');94  });9596  // register error handlers on "listening"97  // so that they disregard definition position.98  this.on('listening', this.registerErrorHandlers.bind(this));99};100101/**102 * When using the vhost() middleware register error handlers.103 */104105Server.prototype.onvhost = function(){106  this.registerErrorHandlers();107};108109/**110 * Register error handlers.111 *112 * @return {Server} for chaining113 * @api public114 */115116Server.prototype.registerErrorHandlers = function(){117  this.errorHandlers.forEach(function(fn){118    this.use(function(err, req, res, next){119      fn.apply(this, arguments);120    });121  }, this);122  return this;123};124125/**126 * Proxy `connect.HTTPServer#use()` to apply settings to127 * mounted applications.128 *129 * @param {String|Function|Server} route130 * @param {Function|Server} middleware131 * @return {Server} for chaining132 * @api public133 */134135Server.prototype.use = function(route, middleware){136  var app, home;137138  if ('string' != typeof route) {139    middleware = route, route = '/';140  }141142  connect.HTTPServer.prototype.use.call(this, route, middleware);143144  // mounted an app145  if (middleware.handle) {146    app = middleware;147    // express app148    if (app.set) {149      home = app.set('home');150      if ('/' == home) home = '';151      app.set('home', app.route + home);152      app.parent = this;153    }154    // mounted hook155    if (app.__mounted) app.__mounted.call(app, this);156  }157158  return this;159};160161/**162 * Assign a callback `fn` which is called163 * when this `Server` is passed to `Server#use()`.164 *165 * Examples:166 *167 *    var app = express.createServer()168 *      , blog = express.createServer();169 *170 *    blog.mounted(function(parent){171 *      // parent is app172 *      // "this" is blog173 *    });174 *175 *    app.use(blog);176 *177 * @param {Function} fn178 * @return {Server} for chaining179 * @api public180 */181182Server.prototype.mounted = function(fn){183  this.__mounted = fn;184  return this;185};186187/**188 * See: view.register.189 *190 * @return {Server} for chaining191 * @api public192 */193194Server.prototype.register = function(){195  view.register.apply(this, arguments);196  return this;197};198199/**200 * Register the given view helpers `obj`. This method201 * can be called several times to apply additional helpers.202 *203 * @param {Object} obj204 * @return {Server} for chaining205 * @api public206 */207208Server.prototype.helpers = 209Server.prototype.locals = function(obj){210  utils.merge(this.viewHelpers, obj);211  return this;212};213214/**215 * Register the given dynamic view helpers `obj`. This method216 * can be called several times to apply additional helpers.217 *218 * @param {Object} obj219 * @return {Server} for chaining220 * @api public221 */222223Server.prototype.dynamicHelpers = function(obj){224  utils.merge(this.dynamicViewHelpers, obj);225  return this;226};227228/**229 * Map the given param placeholder `name`(s) to the given callback `fn`.230 *231 * Param mapping is used to provide pre-conditions to routes232 * which us normalized placeholders. For example ":user_id" may233 * attempt to load the user from the database, where as ":num" may 234 * pass the value through `parseInt(num, 10)`.235 *236 * When the callback function accepts only a single argument, the237 * value of placeholder is passed:238 *239 *    app.param('page', function(n){ return parseInt(n, 10); });240 *241 * After which "/users/:page" would automatically provide us with242 * an integer for `req.params.page`. If desired we could use the callback 243 * signature shown below, and immediately `next(new Error('invalid page'))`244 * when `parseInt` fails.245 *246 * Alternatively the callback may accept the request, response, next, and247 * the value, acting like middlware:248 *249 *     app.param('userId', function(req, res, next, id){250 *       User.find(id, function(err, user){251 *         if (err) {252 *           next(err);253 *         } else if (user) {254 *           req.user = user;255 *           next();256 *         } else {257 *           next(new Error('failed to load user'));258 *         }259 *       });260 *     });261 *262 * Now every time ":userId" is present, the associated user object263 * will be loaded and assigned before the route handler is invoked.264 *265 * @param {String|Array} name266 * @param {Function} fn267 * @return {Server} for chaining268 * @api public269 */270271Server.prototype.param = function(name, fn){272  if (Array.isArray(name)) {273    name.forEach(function(name){274      this.param(name, fn);275    }, this);276  } else {277    if (':' == name[0]) name = name.substr(1);278    this.routes.param(name, fn);279  }280  return this;281};282283/**284 * Assign a custom exception handler callback `fn`.285 * These handlers are always _last_ in the middleware stack.286 *287 * @param {Function} fn288 * @return {Server} for chaining289 * @api public290 */291292Server.prototype.error = function(fn){293  this.errorHandlers.push(fn);294  return this;295};296297/**298 * Register the given callback `fn` for the given `type`.299 *300 * @param {String} type301 * @param {Function} fn302 * @return {Server} for chaining303 * @api public304 */305306Server.prototype.is = function(type, fn){307  if (!fn) return this.isCallbacks[type];308  this.isCallbacks[type] = fn;309  return this;310};311312/**313 * Assign `setting` to `val`, or return `setting`'s value.314 * Mounted servers inherit their parent server's settings.315 *316 * @param {String} setting317 * @param {String} val318 * @return {Server|Mixed} for chaining, or the setting value319 * @api public320 */321322Server.prototype.set = function(setting, val){323  if (val === undefined) {324    if (this.settings.hasOwnProperty(setting)) {325      return this.settings[setting];326    } else if (this.parent) {327      return this.parent.set(setting);328    }329  } else {330    this.settings[setting] = val;331    return this;332  }333};334335/**336 * Check if `setting` is enabled.337 *338 * @param {String} setting339 * @return {Boolean}340 * @api public341 */342343Server.prototype.enabled = function(setting){344  return !!this.set(setting);345};346347/**348 * Check if `setting` is disabled.349 *350 * @param {String} setting351 * @return {Boolean}352 * @api public353 */354355Server.prototype.disabled = function(setting){356  return !this.set(setting);357};358359/**360 * Enable `setting`.361 *362 * @param {String} setting363 * @return {Server} for chaining364 * @api public365 */366367Server.prototype.enable = function(setting){368  return this.set(setting, true);369};370371/**372 * Disable `setting`.373 *374 * @param {String} setting375 * @return {Server} for chaining376 * @api public377 */378379Server.prototype.disable = function(setting){380  return this.set(setting, false);381};382383/**384 * Redirect `key` to `url`.385 *386 * @param {String} key387 * @param {String} url388 * @return {Server} for chaining389 * @api public390 */391392Server.prototype.redirect = function(key, url){393  this.redirects[key] = url;394  return this;395};396397/**398 * Configure callback for the given `env`.399 *400 * @param {String} env401 * @param {Function} fn402 * @return {Server} for chaining403 * @api public404 */405406Server.prototype.configure = function(env, fn){407  if ('function' == typeof env) {408    fn = env, env = 'all';409  }410  if ('all' == env || env == this.settings.env) {411    fn.call(this);412  }413  return this;414};415416// Generate routing methods417418function generateMethod(method){419  Server.prototype[method] = function(path, fn){420    var self = this;421422    // Ensure router is mounted423    if (!this.__usedRouter) {424      this.use(this.router);425    }426427    // Route specific middleware support428    if (arguments.length > 2) {429      var args = Array.prototype.slice.call(arguments, 1);430      fn = args.pop();431      (function stack(middleware){432        middleware.forEach(function(fn){433          if (Array.isArray(fn)) {434            stack(fn);435          } else {436            self[method](path, fn);437          }438        });439      })(args);440    }441442    // Generate the route443    this.routes[method](path, fn);444    return this;445  };446  return arguments.callee;447}448449methods.forEach(generateMethod);450451// Alias delete as "del"452453Server.prototype.del = Server.prototype.delete;