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 fileTake it
Merge branch 'features/https'Tj Holowaychukbefore adoption8261437
lines 1–53why, one step back12/*!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 = [];53docsTj Holowaychukbefore adoption41467d5
line 54why, one step back54 // default "home" to / Merge branch 'features/https'Tj Holowaychukbefore adoption8261437
lines 55–56why, one step back55 this.set('home', '/');56docsTj Holowaychukbefore adoption41467d5
line 57why, one step back57 // set "env" to NODE_ENV, defaulting to "development"Merge branch 'features/https'Tj Holowaychukbefore adoption8261437
lines 58–59why, one step back58 this.set('env', process.env.NODE_ENV || 'development');59docsTj Holowaychukbefore adoption41467d5
line 60why, one step back60 // expose objects to each otherMerge branch 'features/https'Tj Holowaychukbefore adoption8261437
lines 61–62why, one step back61 this.use(function(req, res, next){62 req.query = req.query || {};refactored res.send()Tj Holowaychukbefore adoption3661922
line 63why, one step back63 res.setHeader('X-Powered-By', 'Express');Merge branch 'features/https'Tj Holowaychukbefore adoption8261437
lines 64–67why, one step back64 req.app = res.app = self;65 req.res = res;66 res.req = req;67 req.next = next;docsTj Holowaychukbefore adoption41467d5
line 68why, one step back68 // assign req.queryMerge branch 'features/https'Tj Holowaychukbefore adoption8261437
lines 69–75why, one step back69 if (req.url.indexOf('?') > 0) {70 var query = url.parse(req.url).query;71 req.query = qs.parse(query);72 }73 next();74 });75docsTj Holowaychukbefore adoption41467d5
line 76why, one step back76 // apply middlewaremisc refactoringTj Holowaychukbefore adoption5ec4ea7
line 77why, one step back77 if (middleware) middleware.forEach(self.use.bind(self));Merge branch 'features/https'Tj Holowaychukbefore adoption8261437
line 78why, one step back78docsTj Holowaychukbefore adoption41467d5
line 79why, one step back79 // use router, expose as app.get(), etcMerge branch 'features/https'Tj Holowaychukbefore adoption8261437
lines 80–85why, one step back80 var fn = router(function(app){ self.routes = app; });81 this.__defineGetter__('router', function(){82 this.__usedRouter = true;83 return fn;84 });85docsTj Holowaychukbefore adoption41467d5
line 86why, one step back86 // default production configurationMerge branch 'features/https'Tj Holowaychukbefore adoption8261437
lines 87–90why, one step back87 this.configure('production', function(){88 this.enable('cache views');89 });90refactor errorHandler registrationTj Holowaychukbefore adoption8480869
lines 91–93why, one step back91 // register error handlers on "listening"92 // so that they disregard definition position.93 this.on('listening', this.registerErrorHandlers.bind(this));Merge branch 'features/https'Tj Holowaychukbefore adoption8261437
lines 94–104why, one step back94};9596/**97 * When using the vhost() middleware register error handlers.98 */99100Server.prototype.onvhost = function(){101 this.registerErrorHandlers();102};103104/**refactor errorHandler registrationTj Holowaychukbefore adoption8480869
line 105why, one step back105 * Register error handlers.Merge branch 'features/https'Tj Holowaychukbefore adoption8261437
lines 106–130why, one step back106 *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){Fixed mounting of non-express serversTj Holowaychukbefore adoption2dae6d8
lines 131–132why, one step back131 var app, home;132misc refactoringTj Holowaychukbefore adoption7c15cde
line 133why, one step back133 if ('string' != typeof route) {Merge branch 'features/https'Tj Holowaychukbefore adoption8261437
lines 134–138why, one step back134 middleware = route, route = '/';135 }136137 connect.HTTPServer.prototype.use.call(this, route, middleware);138misc refactoringTj Holowaychukbefore adoption7c15cde
lines 139–140why, one step back139 // mounted an app140 if (middleware.handle) {Fixed mounting of non-express serversTj Holowaychukbefore adoption2dae6d8
lines 141–148why, one step back141 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 }misc refactoringTj Holowaychukbefore adoption7c15cde
line 149why, one step back149 // mounted hookMerge branch 'features/https'Tj Holowaychukbefore adoption8261437
lines 150–161why, one step back150 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 *misc refactoringTj Holowaychukbefore adoption7c15cde
lines 162–163why, one step back162 * var app = express.createServer()163 * , blog = express.createServer();Merge branch 'features/https'Tj Holowaychukbefore adoption8261437
lines 164–165why, one step back164 *165 * blog.mounted(function(parent){misc refactoringTj Holowaychukbefore adoption7c15cde
lines 166–167why, one step back166 * // parent is app167 * // "this" is blogMerge branch 'features/https'Tj Holowaychukbefore adoption8261437
lines 168–243why, one step back168 * });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 *misc refactoringTj Holowaychukbefore adoption7c15cde
lines 244–255why, one step back244 * 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 * });Merge branch 'features/https'Tj Holowaychukbefore adoption8261437
lines 256–401why, one step back256 *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){misc refactoringTj Holowaychukbefore adoption7c15cde
line 402why, one step back402 if ('function' == typeof env) {Merge branch 'features/https'Tj Holowaychukbefore adoption8261437
lines 403–448why, one step back403 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;