http.js
This file
Path
lib/http.js
464 lines · 9.9 KiB · JavaScript
Last changed by
Merge branch 'integration'Tj Holowaychukbefore adoptionf3c068a
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 = 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, handle;137138 if ('string' != typeof route) {139 middleware = route, route = '/';140 }141142 // express app143 if (middleware.handle && middleware.set) app = middleware;144145 // restore .app property on req and res146 if (app) {147 app.route = route;148 middleware = function(req, res, next) {149 var orig = req.app;150 app.handle(req, res, function(err){151 req.app = res.app = orig;152 next(err);153 });154 };155 }156157 connect.HTTPServer.prototype.use.call(this, route, middleware);158159 // mounted an app, invoke the hook160 // and adjust some settings161 if (app) {162 home = app.set('home');163 if ('/' == home) home = '';164 app.set('home', app.route + home);165 app.parent = this;166 if (app.__mounted) app.__mounted.call(app, this);167 }168169 return this;170};171172/**173 * Assign a callback `fn` which is called174 * when this `Server` is passed to `Server#use()`.175 *176 * Examples:177 *178 * var app = express.createServer()179 * , blog = express.createServer();180 *181 * blog.mounted(function(parent){182 * // parent is app183 * // "this" is blog184 * });185 *186 * app.use(blog);187 *188 * @param {Function} fn189 * @return {Server} for chaining190 * @api public191 */192193Server.prototype.mounted = function(fn){194 this.__mounted = fn;195 return this;196};197198/**199 * See: view.register.200 *201 * @return {Server} for chaining202 * @api public203 */204205Server.prototype.register = function(){206 view.register.apply(this, arguments);207 return this;208};209210/**211 * Register the given view helpers `obj`. This method212 * can be called several times to apply additional helpers.213 *214 * @param {Object} obj215 * @return {Server} for chaining216 * @api public217 */218219Server.prototype.helpers =220Server.prototype.locals = function(obj){221 utils.merge(this.viewHelpers, obj);222 return this;223};224225/**226 * Register the given dynamic view helpers `obj`. This method227 * can be called several times to apply additional helpers.228 *229 * @param {Object} obj230 * @return {Server} for chaining231 * @api public232 */233234Server.prototype.dynamicHelpers = function(obj){235 utils.merge(this.dynamicViewHelpers, obj);236 return this;237};238239/**240 * Map the given param placeholder `name`(s) to the given callback `fn`.241 *242 * Param mapping is used to provide pre-conditions to routes243 * which us normalized placeholders. For example ":user_id" may244 * attempt to load the user from the database, where as ":num" may245 * pass the value through `parseInt(num, 10)`.246 *247 * When the callback function accepts only a single argument, the248 * value of placeholder is passed:249 *250 * app.param('page', function(n){ return parseInt(n, 10); });251 *252 * After which "/users/:page" would automatically provide us with253 * an integer for `req.params.page`. If desired we could use the callback254 * signature shown below, and immediately `next(new Error('invalid page'))`255 * when `parseInt` fails.256 *257 * Alternatively the callback may accept the request, response, next, and258 * the value, acting like middlware:259 *260 * app.param('userId', function(req, res, next, id){261 * User.find(id, function(err, user){262 * if (err) {263 * next(err);264 * } else if (user) {265 * req.user = user;266 * next();267 * } else {268 * next(new Error('failed to load user'));269 * }270 * });271 * });272 *273 * Now every time ":userId" is present, the associated user object274 * will be loaded and assigned before the route handler is invoked.275 *276 * @param {String|Array} name277 * @param {Function} fn278 * @return {Server} for chaining279 * @api public280 */281282Server.prototype.param = function(name, fn){283 if (Array.isArray(name)) {284 name.forEach(function(name){285 this.param(name, fn);286 }, this);287 } else {288 if (':' == name[0]) name = name.substr(1);289 this.routes.param(name, fn);290 }291 return this;292};293294/**295 * Assign a custom exception handler callback `fn`.296 * These handlers are always _last_ in the middleware stack.297 *298 * @param {Function} fn299 * @return {Server} for chaining300 * @api public301 */302303Server.prototype.error = function(fn){304 this.errorHandlers.push(fn);305 return this;306};307308/**309 * Register the given callback `fn` for the given `type`.310 *311 * @param {String} type312 * @param {Function} fn313 * @return {Server} for chaining314 * @api public315 */316317Server.prototype.is = function(type, fn){318 if (!fn) return this.isCallbacks[type];319 this.isCallbacks[type] = fn;320 return this;321};322323/**324 * Assign `setting` to `val`, or return `setting`'s value.325 * Mounted servers inherit their parent server's settings.326 *327 * @param {String} setting328 * @param {String} val329 * @return {Server|Mixed} for chaining, or the setting value330 * @api public331 */332333Server.prototype.set = function(setting, val){334 if (val === undefined) {335 if (this.settings.hasOwnProperty(setting)) {336 return this.settings[setting];337 } else if (this.parent) {338 return this.parent.set(setting);339 }340 } else {341 this.settings[setting] = val;342 return this;343 }344};345346/**347 * Check if `setting` is enabled.348 *349 * @param {String} setting350 * @return {Boolean}351 * @api public352 */353354Server.prototype.enabled = function(setting){355 return !!this.set(setting);356};357358/**359 * Check if `setting` is disabled.360 *361 * @param {String} setting362 * @return {Boolean}363 * @api public364 */365366Server.prototype.disabled = function(setting){367 return !this.set(setting);368};369370/**371 * Enable `setting`.372 *373 * @param {String} setting374 * @return {Server} for chaining375 * @api public376 */377378Server.prototype.enable = function(setting){379 return this.set(setting, true);380};381382/**383 * Disable `setting`.384 *385 * @param {String} setting386 * @return {Server} for chaining387 * @api public388 */389390Server.prototype.disable = function(setting){391 return this.set(setting, false);392};393394/**395 * Redirect `key` to `url`.396 *397 * @param {String} key398 * @param {String} url399 * @return {Server} for chaining400 * @api public401 */402403Server.prototype.redirect = function(key, url){404 this.redirects[key] = url;405 return this;406};407408/**409 * Configure callback for the given `env`.410 *411 * @param {String} env412 * @param {Function} fn413 * @return {Server} for chaining414 * @api public415 */416417Server.prototype.configure = function(env, fn){418 if ('function' == typeof env) {419 fn = env, env = 'all';420 }421 if ('all' == env || env == this.settings.env) {422 fn.call(this);423 }424 return this;425};426427// Generate routing methods428429function generateMethod(method){430 Server.prototype[method] = function(path, fn){431 var self = this;432433 // Ensure router is mounted434 if (!this.__usedRouter) {435 this.use(this.router);436 }437438 // Route specific middleware support439 if (arguments.length > 2) {440 var args = Array.prototype.slice.call(arguments, 1);441 fn = args.pop();442 (function stack(middleware){443 middleware.forEach(function(fn){444 if (Array.isArray(fn)) {445 stack(fn);446 } else {447 self[method](path, fn);448 }449 });450 })(args);451 }452453 // Generate the route454 this.routes[method](path, fn);455 return this;456 };457 return arguments.callee;458}459460methods.forEach(generateMethod);461462// Alias delete as "del"463464Server.prototype.del = Server.prototype.delete;