http.js
This file
Path
lib/http.js
544 lines · 10.9 KiB · JavaScript
Last changed by
docsTj Holowaychukbefore adoptionf46ae9f
History of this fileTake 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 , url = require('url')20 , utils = connect.utils;2122/**23 * Expose `HTTPServer`.24 */2526exports = module.exports = HTTPServer;2728/**29 * Server proto.30 */3132var app = HTTPServer.prototype;3334/**35 * Initialize a new `HTTPServer` with optional `middleware`.36 *37 * @param {Array} middleware38 * @api public39 */4041function HTTPServer(middleware){42 connect.HTTPServer.call(this, []);43 this.init(middleware);44};4546/**47 * Inherit from `connect.HTTPServer`.48 */4950app.__proto__ = connect.HTTPServer.prototype;5152/**53 * Initialize the server.54 *55 * @param {Array} middleware56 * @api private57 */5859app.init = function(middleware){60 var self = this;61 this.cache = {};62 this.settings = {};63 this.redirects = {};64 this.isCallbacks = {};65 this._locals = {};66 this.dynamicViewHelpers = {};67 this.errorHandlers = [];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 // register error handlers on "listening"115 // so that they disregard definition position.116 this.on('listening', this.registerErrorHandlers.bind(this));117118 // route manipulation methods119 methods.forEach(function(method){120 self.lookup[method] = function(path){121 return self.routes.lookup(method, path);122 };123124 self.match[method] = function(path){125 return self.routes.match(method, path);126 };127128 self.remove[method] = function(path){129 return self.routes.lookup(method, path).remove();130 };131 });132133 // del -> delete134 self.lookup.del = self.lookup.delete;135 self.match.del = self.match.delete;136 self.remove.del = self.remove.delete;137};138139/**140 * Remove routes matching the given `path`.141 *142 * @param {Route} path143 * @return {Boolean}144 * @api public145 */146147app.remove = function(path){148 return this.routes.lookup('all', path).remove();149};150151/**152 * Lookup routes defined with a path153 * equivalent to `path`.154 *155 * @param {Stirng} path156 * @return {Array}157 * @api public158 */159160app.lookup = function(path){161 return this.routes.lookup('all', path);162};163164/**165 * Lookup routes matching the given `url`.166 *167 * @param {Stirng} url168 * @return {Array}169 * @api public170 */171172app.match = function(url){173 return this.routes.match('all', url);174};175176/**177 * When using the vhost() middleware register error handlers.178 */179180app.onvhost = function(){181 this.registerErrorHandlers();182};183184/**185 * Register error handlers.186 *187 * @return {Server} for chaining188 * @api public189 */190191app.registerErrorHandlers = function(){192 this.errorHandlers.forEach(function(fn){193 this.use(function(err, req, res, next){194 fn.apply(this, arguments);195 });196 }, this);197 return this;198};199200/**201 * Proxy `connect.HTTPServer#use()` to apply settings to202 * mounted applications.203 *204 * @param {String|Function|Server} route205 * @param {Function|Server} middleware206 * @return {Server} for chaining207 * @api public208 */209210app.use = function(route, middleware){211 var app, home, handle;212213 if ('string' != typeof route) {214 middleware = route, route = '/';215 }216217 // express app218 if (middleware.handle && middleware.set) app = middleware;219220 // restore .app property on req and res221 if (app) {222 app.route = route;223 middleware = function(req, res, next) {224 var orig = req.app;225 app.handle(req, res, function(err){226 req.app = res.app = orig;227 next(err);228 });229 };230 }231232 connect.HTTPServer.prototype.use.call(this, route, middleware);233234 // mounted an app, invoke the hook235 // and adjust some settings236 if (app) {237 home = app.set('home');238 if ('/' == home) home = '';239 app.set('home', app.route + home);240 app.parent = this;241 if (app.__mounted) app.__mounted.call(app, this);242 }243244 return this;245};246247/**248 * Assign a callback `fn` which is called249 * when this `Server` is passed to `Server#use()`.250 *251 * Examples:252 *253 * var app = express.createServer()254 * , blog = express.createServer();255 *256 * blog.mounted(function(parent){257 * // parent is app258 * // "this" is blog259 * });260 *261 * app.use(blog);262 *263 * @param {Function} fn264 * @return {Server} for chaining265 * @api public266 */267268app.mounted = function(fn){269 this.__mounted = fn;270 return this;271};272273/**274 * See: view.register.275 *276 * @return {Server} for chaining277 * @api public278 */279280app.register = function(){281 view.register.apply(this, arguments);282 return this;283};284285/**286 * Register the given view helpers `obj`. This method287 * can be called several times to apply additional helpers.288 *289 * @param {Object} obj290 * @return {Server} for chaining291 * @api public292 */293294app.helpers =295app.locals = function(obj){296 utils.merge(this._locals, obj);297 return this;298};299300/**301 * Register the given dynamic view helpers `obj`. This method302 * can be called several times to apply additional helpers.303 *304 * @param {Object} obj305 * @return {Server} for chaining306 * @api public307 */308309app.dynamicHelpers = function(obj){310 utils.merge(this.dynamicViewHelpers, obj);311 return this;312};313314/**315 * Map the given param placeholder `name`(s) to the given callback `fn`.316 *317 * Param mapping is used to provide pre-conditions to routes318 * which us normalized placeholders. This callback has the same319 * signature as regular middleware, for example below when ":userId"320 * is used this function will be invoked in an attempt to load the user.321 *322 * app.param('userId', function(req, res, next, id){323 * User.find(id, function(err, user){324 * if (err) {325 * next(err);326 * } else if (user) {327 * req.user = user;328 * next();329 * } else {330 * next(new Error('failed to load user'));331 * }332 * });333 * });334 *335 * @param {String|Array|Function} name336 * @param {Function} fn337 * @return {Server} for chaining338 * @api public339 */340341app.param = function(name, fn){342 // array343 if (Array.isArray(name)) {344 name.forEach(function(name){345 this.param(name, fn);346 }, this);347 // param logic348 } else if ('function' == typeof name) {349 this.routes.param(name);350 // single351 } else {352 if (':' == name[0]) name = name.substr(1);353 this.routes.param(name, fn);354 }355356 return this;357};358359/**360 * Assign a custom exception handler callback `fn`.361 * These handlers are always _last_ in the middleware stack.362 *363 * @param {Function} fn364 * @return {Server} for chaining365 * @api public366 */367368app.error = function(fn){369 this.errorHandlers.push(fn);370 return this;371};372373/**374 * Register the given callback `fn` for the given `type`.375 *376 * @param {String} type377 * @param {Function} fn378 * @return {Server} for chaining379 * @api public380 */381382app.is = function(type, fn){383 if (!fn) return this.isCallbacks[type];384 this.isCallbacks[type] = fn;385 return this;386};387388/**389 * Assign `setting` to `val`, or return `setting`'s value.390 * Mounted servers inherit their parent server's settings.391 *392 * @param {String} setting393 * @param {String} val394 * @return {Server|Mixed} for chaining, or the setting value395 * @api public396 */397398app.set = function(setting, val){399 if (val === undefined) {400 if (this.settings.hasOwnProperty(setting)) {401 return this.settings[setting];402 } else if (this.parent) {403 return this.parent.set(setting);404 }405 } else {406 this.settings[setting] = val;407 return this;408 }409};410411/**412 * Check if `setting` is enabled.413 *414 * @param {String} setting415 * @return {Boolean}416 * @api public417 */418419app.enabled = function(setting){420 return !!this.set(setting);421};422423/**424 * Check if `setting` is disabled.425 *426 * @param {String} setting427 * @return {Boolean}428 * @api public429 */430431app.disabled = function(setting){432 return !this.set(setting);433};434435/**436 * Enable `setting`.437 *438 * @param {String} setting439 * @return {Server} for chaining440 * @api public441 */442443app.enable = function(setting){444 return this.set(setting, true);445};446447/**448 * Disable `setting`.449 *450 * @param {String} setting451 * @return {Server} for chaining452 * @api public453 */454455app.disable = function(setting){456 return this.set(setting, false);457};458459/**460 * Redirect `key` to `url`.461 *462 * @param {String} key463 * @param {String} url464 * @return {Server} for chaining465 * @api public466 */467468app.redirect = function(key, url){469 this.redirects[key] = url;470 return this;471};472473/**474 * Configure callback for zero or more envs,475 * when no env is specified that callback will476 * be invoked for all environments. Any combination477 * can be used multiple times, in any order desired.478 *479 * Examples:480 *481 * app.configure(function(){482 * // executed for all envs483 * });484 *485 * app.configure('stage', function(){486 * // executed staging env487 * });488 *489 * app.configure('stage', 'production', function(){490 * // executed for stage and production491 * });492 *493 * @param {String} env...494 * @param {Function} fn495 * @return {Server} for chaining496 * @api public497 */498499app.configure = function(env, fn){500 var envs = 'all'501 , args = toArray(arguments);502 fn = args.pop();503 if (args.length) envs = args;504 if ('all' == envs || ~envs.indexOf(this.settings.env)) fn.call(this);505 return this;506};507508/**509 * Delegate `.VERB(...)` calls to `.route(VERB, ...)`.510 */511512methods.forEach(function(method){513 app[method] = function(path){514 if (1 == arguments.length) return this.routes.lookup(method, path);515 var args = [method].concat(toArray(arguments));516 if (!this.__usedRouter) this.use(this.router);517 return this.routes._route.apply(this.routes, args);518 }519});520521/**522 * Special-cased "all" method, applying the given route `path`,523 * middleware, and callback to _every_ HTTP method.524 *525 * @param {String} path526 * @param {Function} ...527 * @return {Server} for chaining528 * @api public529 */530531app.all = function(path){532 var args = arguments;533 if (1 == args.length) return this.routes.lookup('all', path);534 methods.forEach(function(method){535 if ('all' == method) return;536 app[method].apply(this, args);537 }, this);538 return this;539};540541// del -> delete alias542543app.del = app.delete;544