Skip to content
Myr

http.js

This file

Path

lib/http.js

448 lines · 9.5 KiB · JavaScript

Last changed by

Fixed mounting of non-express serversTj Holowaychukbefore adoption2dae6d8

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 production configuration87  this.configure('production', function(){88    this.enable('cache views');89  });9091  // register error handlers on "listening"92  // so that they disregard definition position.93  this.on('listening', this.registerErrorHandlers.bind(this));94};9596/**97 * When using the vhost() middleware register error handlers.98 */99100Server.prototype.onvhost = function(){101  this.registerErrorHandlers();102};103104/**105 * Register error handlers.106 *107 * @return {Server} for chaining108 * @api public109 */110111Server.prototype.registerErrorHandlers = function(){112  this.errorHandlers.forEach(function(fn){113    this.use(function(err, req, res, next){114      fn.apply(this, arguments);115    });116  }, this);117  return this;118};119120/**121 * Proxy `connect.HTTPServer#use()` to apply settings to122 * mounted applications.123 *124 * @param {String|Function|Server} route125 * @param {Function|Server} middleware126 * @return {Server} for chaining127 * @api public128 */129130Server.prototype.use = function(route, middleware){131  var app, home;132133  if ('string' != typeof route) {134    middleware = route, route = '/';135  }136137  connect.HTTPServer.prototype.use.call(this, route, middleware);138139  // mounted an app140  if (middleware.handle) {141    app = middleware;142    // express app143    if (app.set) {144      home = app.set('home');145      if ('/' == home) home = '';146      app.set('home', app.route + home);147      app.parent = this;148    }149    // mounted hook150    if (app.__mounted) app.__mounted.call(app, this);151  }152153  return this;154};155156/**157 * Assign a callback `fn` which is called158 * when this `Server` is passed to `Server#use()`.159 *160 * Examples:161 *162 *    var app = express.createServer()163 *      , blog = express.createServer();164 *165 *    blog.mounted(function(parent){166 *      // parent is app167 *      // "this" is blog168 *    });169 *170 *    app.use(blog);171 *172 * @param {Function} fn173 * @return {Server} for chaining174 * @api public175 */176177Server.prototype.mounted = function(fn){178  this.__mounted = fn;179  return this;180};181182/**183 * See: view.register.184 *185 * @return {Server} for chaining186 * @api public187 */188189Server.prototype.register = function(){190  view.register.apply(this, arguments);191  return this;192};193194/**195 * Register the given view helpers `obj`. This method196 * can be called several times to apply additional helpers.197 *198 * @param {Object} obj199 * @return {Server} for chaining200 * @api public201 */202203Server.prototype.helpers = 204Server.prototype.locals = function(obj){205  utils.merge(this.viewHelpers, obj);206  return this;207};208209/**210 * Register the given dynamic view helpers `obj`. This method211 * can be called several times to apply additional helpers.212 *213 * @param {Object} obj214 * @return {Server} for chaining215 * @api public216 */217218Server.prototype.dynamicHelpers = function(obj){219  utils.merge(this.dynamicViewHelpers, obj);220  return this;221};222223/**224 * Map the given param placeholder `name`(s) to the given callback `fn`.225 *226 * Param mapping is used to provide pre-conditions to routes227 * which us normalized placeholders. For example ":user_id" may228 * attempt to load the user from the database, where as ":num" may 229 * pass the value through `parseInt(num, 10)`.230 *231 * When the callback function accepts only a single argument, the232 * value of placeholder is passed:233 *234 *    app.param('page', function(n){ return parseInt(n, 10); });235 *236 * After which "/users/:page" would automatically provide us with237 * an integer for `req.params.page`. If desired we could use the callback 238 * signature shown below, and immediately `next(new Error('invalid page'))`239 * when `parseInt` fails.240 *241 * Alternatively the callback may accept the request, response, next, and242 * the value, acting like middlware:243 *244 *     app.param('userId', function(req, res, next, id){245 *       User.find(id, function(err, user){246 *         if (err) {247 *           next(err);248 *         } else if (user) {249 *           req.user = user;250 *           next();251 *         } else {252 *           next(new Error('failed to load user'));253 *         }254 *       });255 *     });256 *257 * Now every time ":userId" is present, the associated user object258 * will be loaded and assigned before the route handler is invoked.259 *260 * @param {String|Array} name261 * @param {Function} fn262 * @return {Server} for chaining263 * @api public264 */265266Server.prototype.param = function(name, fn){267  if (Array.isArray(name)) {268    name.forEach(function(name){269      this.param(name, fn);270    }, this);271  } else {272    if (':' == name[0]) name = name.substr(1);273    this.routes.param(name, fn);274  }275  return this;276};277278/**279 * Assign a custom exception handler callback `fn`.280 * These handlers are always _last_ in the middleware stack.281 *282 * @param {Function} fn283 * @return {Server} for chaining284 * @api public285 */286287Server.prototype.error = function(fn){288  this.errorHandlers.push(fn);289  return this;290};291292/**293 * Register the given callback `fn` for the given `type`.294 *295 * @param {String} type296 * @param {Function} fn297 * @return {Server} for chaining298 * @api public299 */300301Server.prototype.is = function(type, fn){302  if (!fn) return this.isCallbacks[type];303  this.isCallbacks[type] = fn;304  return this;305};306307/**308 * Assign `setting` to `val`, or return `setting`'s value.309 * Mounted servers inherit their parent server's settings.310 *311 * @param {String} setting312 * @param {String} val313 * @return {Server|Mixed} for chaining, or the setting value314 * @api public315 */316317Server.prototype.set = function(setting, val){318  if (val === undefined) {319    if (this.settings.hasOwnProperty(setting)) {320      return this.settings[setting];321    } else if (this.parent) {322      return this.parent.set(setting);323    }324  } else {325    this.settings[setting] = val;326    return this;327  }328};329330/**331 * Check if `setting` is enabled.332 *333 * @param {String} setting334 * @return {Boolean}335 * @api public336 */337338Server.prototype.enabled = function(setting){339  return !!this.set(setting);340};341342/**343 * Check if `setting` is disabled.344 *345 * @param {String} setting346 * @return {Boolean}347 * @api public348 */349350Server.prototype.disabled = function(setting){351  return !this.set(setting);352};353354/**355 * Enable `setting`.356 *357 * @param {String} setting358 * @return {Server} for chaining359 * @api public360 */361362Server.prototype.enable = function(setting){363  return this.set(setting, true);364};365366/**367 * Disable `setting`.368 *369 * @param {String} setting370 * @return {Server} for chaining371 * @api public372 */373374Server.prototype.disable = function(setting){375  return this.set(setting, false);376};377378/**379 * Redirect `key` to `url`.380 *381 * @param {String} key382 * @param {String} url383 * @return {Server} for chaining384 * @api public385 */386387Server.prototype.redirect = function(key, url){388  this.redirects[key] = url;389  return this;390};391392/**393 * Configure callback for the given `env`.394 *395 * @param {String} env396 * @param {Function} fn397 * @return {Server} for chaining398 * @api public399 */400401Server.prototype.configure = function(env, fn){402  if ('function' == typeof env) {403    fn = env, env = 'all';404  }405  if ('all' == env || env == this.settings.env) {406    fn.call(this);407  }408  return this;409};410411// Generate routing methods412413function generateMethod(method){414  Server.prototype[method] = function(path, fn){415    var self = this;416417    // Ensure router is mounted418    if (!this.__usedRouter) {419      this.use(this.router);420    }421422    // Route specific middleware support423    if (arguments.length > 2) {424      var args = Array.prototype.slice.call(arguments, 1);425      fn = args.pop();426      (function stack(middleware){427        middleware.forEach(function(fn){428          if (Array.isArray(fn)) {429            stack(fn);430          } else {431            self[method](path, fn);432          }433        });434      })(args);435    }436437    // Generate the route438    this.routes[method](path, fn);439    return this;440  };441  return arguments.callee;442}443444methods.forEach(generateMethod);445446// Alias delete as "del"447448Server.prototype.del = Server.prototype.delete;