http.js
This file
Path
lib/http.js
467 lines · 10.0 KiB · JavaScript
Last changed by
Added 'settings' local variable, containing the app's settingsTj Holowaychukbefore adoption9d2bd29
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 = [];53Merge branch 'integration'Tj Holowaychukbefore adoptionf3c068a
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 });85Added 'settings' local variable, containing the app's settingsTj Holowaychukbefore adoption9d2bd29
lines 86–88why, one step back86 // default locals87 this.locals({ settings: this.settings });88Added view resolution hints when in developmentTj Holowaychukbefore adoptionf1f1261
lines 89–93why, one step back89 // default development configuration90 this.configure('development', function(){91 this.enable('hints');92 });93docsTj Holowaychukbefore adoption41467d5
line 94why, one step back94 // default production configurationMerge branch 'features/https'Tj Holowaychukbefore adoption8261437
lines 95–98why, one step back95 this.configure('production', function(){96 this.enable('cache views');97 });98refactor errorHandler registrationTj Holowaychukbefore adoption8480869
lines 99–101why, one step back99 // register error handlers on "listening"100 // so that they disregard definition position.101 this.on('listening', this.registerErrorHandlers.bind(this));Merge branch 'features/https'Tj Holowaychukbefore adoption8261437
lines 102–112why, one step back102};103104/**105 * When using the vhost() middleware register error handlers.106 */107108Server.prototype.onvhost = function(){109 this.registerErrorHandlers();110};111112/**refactor errorHandler registrationTj Holowaychukbefore adoption8480869
line 113why, one step back113 * Register error handlers.Merge branch 'features/https'Tj Holowaychukbefore adoption8261437
lines 114–138why, one step back114 *115 * @return {Server} for chaining116 * @api public117 */118119Server.prototype.registerErrorHandlers = function(){120 this.errorHandlers.forEach(function(fn){121 this.use(function(err, req, res, next){122 fn.apply(this, arguments);123 });124 }, this);125 return this;126};127128/**129 * Proxy `connect.HTTPServer#use()` to apply settings to130 * mounted applications.131 *132 * @param {String|Function|Server} route133 * @param {Function|Server} middleware134 * @return {Server} for chaining135 * @api public136 */137138Server.prototype.use = function(route, middleware){Merge branch 'integration'Tj Holowaychukbefore adoptionf3c068a
line 139why, one step back139 var app, home, handle;Fixed mounting of non-express serversTj Holowaychukbefore adoption2dae6d8
line 140why, one step back140misc refactoringTj Holowaychukbefore adoption7c15cde
line 141why, one step back141 if ('string' != typeof route) {Merge branch 'features/https'Tj Holowaychukbefore adoption8261437
lines 142–144why, one step back142 middleware = route, route = '/';143 }144Merge branch 'integration'Tj Holowaychukbefore adoptionf3c068a
lines 145–159why, one step back145 // express app146 if (middleware.handle && middleware.set) app = middleware;147148 // restore .app property on req and res149 if (app) {150 app.route = route;151 middleware = function(req, res, next) {152 var orig = req.app;153 app.handle(req, res, function(err){154 req.app = res.app = orig;155 next(err);156 });157 };158 }159Merge branch 'features/https'Tj Holowaychukbefore adoption8261437
lines 160–161why, one step back160 connect.HTTPServer.prototype.use.call(this, route, middleware);161Merge branch 'integration'Tj Holowaychukbefore adoptionf3c068a
lines 162–168why, one step back162 // mounted an app, invoke the hook163 // and adjust some settings164 if (app) {165 home = app.set('home');166 if ('/' == home) home = '';167 app.set('home', app.route + home);168 app.parent = this;Merge branch 'features/https'Tj Holowaychukbefore adoption8261437
lines 169–180why, one step back169 if (app.__mounted) app.__mounted.call(app, this);170 }171172 return this;173};174175/**176 * Assign a callback `fn` which is called177 * when this `Server` is passed to `Server#use()`.178 *179 * Examples:180 *misc refactoringTj Holowaychukbefore adoption7c15cde
lines 181–182why, one step back181 * var app = express.createServer()182 * , blog = express.createServer();Merge branch 'features/https'Tj Holowaychukbefore adoption8261437
lines 183–184why, one step back183 *184 * blog.mounted(function(parent){misc refactoringTj Holowaychukbefore adoption7c15cde
lines 185–186why, one step back185 * // parent is app186 * // "this" is blogMerge branch 'features/https'Tj Holowaychukbefore adoption8261437
lines 187–221why, one step back187 * });188 *189 * app.use(blog);190 *191 * @param {Function} fn192 * @return {Server} for chaining193 * @api public194 */195196Server.prototype.mounted = function(fn){197 this.__mounted = fn;198 return this;199};200201/**202 * See: view.register.203 *204 * @return {Server} for chaining205 * @api public206 */207208Server.prototype.register = function(){209 view.register.apply(this, arguments);210 return this;211};212213/**214 * Register the given view helpers `obj`. This method215 * can be called several times to apply additional helpers.216 *217 * @param {Object} obj218 * @return {Server} for chaining219 * @api public220 */221Merge branch 'integration'Tj Holowaychukbefore adoptionf3c068a
line 222why, one step back222Server.prototype.helpers =Merge branch 'features/https'Tj Holowaychukbefore adoption8261437
lines 223–246why, one step back223Server.prototype.locals = function(obj){224 utils.merge(this.viewHelpers, obj);225 return this;226};227228/**229 * Register the given dynamic view helpers `obj`. This method230 * can be called several times to apply additional helpers.231 *232 * @param {Object} obj233 * @return {Server} for chaining234 * @api public235 */236237Server.prototype.dynamicHelpers = function(obj){238 utils.merge(this.dynamicViewHelpers, obj);239 return this;240};241242/**243 * Map the given param placeholder `name`(s) to the given callback `fn`.244 *245 * Param mapping is used to provide pre-conditions to routes246 * which us normalized placeholders. For example ":user_id" mayMerge branch 'integration'Tj Holowaychukbefore adoptionf3c068a
line 247why, one step back247 * attempt to load the user from the database, where as ":num" mayMerge branch 'features/https'Tj Holowaychukbefore adoption8261437
lines 248–255why, one step back248 * pass the value through `parseInt(num, 10)`.249 *250 * When the callback function accepts only a single argument, the251 * value of placeholder is passed:252 *253 * app.param('page', function(n){ return parseInt(n, 10); });254 *255 * After which "/users/:page" would automatically provide us withMerge branch 'integration'Tj Holowaychukbefore adoptionf3c068a
line 256why, one step back256 * an integer for `req.params.page`. If desired we could use the callbackMerge branch 'features/https'Tj Holowaychukbefore adoption8261437
lines 257–262why, one step back257 * signature shown below, and immediately `next(new Error('invalid page'))`258 * when `parseInt` fails.259 *260 * Alternatively the callback may accept the request, response, next, and261 * the value, acting like middlware:262 *misc refactoringTj Holowaychukbefore adoption7c15cde
lines 263–274why, one step back263 * app.param('userId', function(req, res, next, id){264 * User.find(id, function(err, user){265 * if (err) {266 * next(err);267 * } else if (user) {268 * req.user = user;269 * next();270 * } else {271 * next(new Error('failed to load user'));272 * }273 * });274 * });Merge branch 'features/https'Tj Holowaychukbefore adoption8261437
lines 275–420why, one step back275 *276 * Now every time ":userId" is present, the associated user object277 * will be loaded and assigned before the route handler is invoked.278 *279 * @param {String|Array} name280 * @param {Function} fn281 * @return {Server} for chaining282 * @api public283 */284285Server.prototype.param = function(name, fn){286 if (Array.isArray(name)) {287 name.forEach(function(name){288 this.param(name, fn);289 }, this);290 } else {291 if (':' == name[0]) name = name.substr(1);292 this.routes.param(name, fn);293 }294 return this;295};296297/**298 * Assign a custom exception handler callback `fn`.299 * These handlers are always _last_ in the middleware stack.300 *301 * @param {Function} fn302 * @return {Server} for chaining303 * @api public304 */305306Server.prototype.error = function(fn){307 this.errorHandlers.push(fn);308 return this;309};310311/**312 * Register the given callback `fn` for the given `type`.313 *314 * @param {String} type315 * @param {Function} fn316 * @return {Server} for chaining317 * @api public318 */319320Server.prototype.is = function(type, fn){321 if (!fn) return this.isCallbacks[type];322 this.isCallbacks[type] = fn;323 return this;324};325326/**327 * Assign `setting` to `val`, or return `setting`'s value.328 * Mounted servers inherit their parent server's settings.329 *330 * @param {String} setting331 * @param {String} val332 * @return {Server|Mixed} for chaining, or the setting value333 * @api public334 */335336Server.prototype.set = function(setting, val){337 if (val === undefined) {338 if (this.settings.hasOwnProperty(setting)) {339 return this.settings[setting];340 } else if (this.parent) {341 return this.parent.set(setting);342 }343 } else {344 this.settings[setting] = val;345 return this;346 }347};348349/**350 * Check if `setting` is enabled.351 *352 * @param {String} setting353 * @return {Boolean}354 * @api public355 */356357Server.prototype.enabled = function(setting){358 return !!this.set(setting);359};360361/**362 * Check if `setting` is disabled.363 *364 * @param {String} setting365 * @return {Boolean}366 * @api public367 */368369Server.prototype.disabled = function(setting){370 return !this.set(setting);371};372373/**374 * Enable `setting`.375 *376 * @param {String} setting377 * @return {Server} for chaining378 * @api public379 */380381Server.prototype.enable = function(setting){382 return this.set(setting, true);383};384385/**386 * Disable `setting`.387 *388 * @param {String} setting389 * @return {Server} for chaining390 * @api public391 */392393Server.prototype.disable = function(setting){394 return this.set(setting, false);395};396397/**398 * Redirect `key` to `url`.399 *400 * @param {String} key401 * @param {String} url402 * @return {Server} for chaining403 * @api public404 */405406Server.prototype.redirect = function(key, url){407 this.redirects[key] = url;408 return this;409};410411/**412 * Configure callback for the given `env`.413 *414 * @param {String} env415 * @param {Function} fn416 * @return {Server} for chaining417 * @api public418 */419420Server.prototype.configure = function(env, fn){misc refactoringTj Holowaychukbefore adoption7c15cde
line 421why, one step back421 if ('function' == typeof env) {Merge branch 'features/https'Tj Holowaychukbefore adoption8261437
lines 422–467why, one step back422 fn = env, env = 'all';423 }424 if ('all' == env || env == this.settings.env) {425 fn.call(this);426 }427 return this;428};429430// Generate routing methods431432function generateMethod(method){433 Server.prototype[method] = function(path, fn){434 var self = this;435436 // Ensure router is mounted437 if (!this.__usedRouter) {438 this.use(this.router);439 }440441 // Route specific middleware support442 if (arguments.length > 2) {443 var args = Array.prototype.slice.call(arguments, 1);444 fn = args.pop();445 (function stack(middleware){446 middleware.forEach(function(fn){447 if (Array.isArray(fn)) {448 stack(fn);449 } else {450 self[method](path, fn);451 }452 });453 })(args);454 }455456 // Generate the route457 this.routes[method](path, fn);458 return this;459 };460 return arguments.callee;461}462463methods.forEach(generateMethod);464465// Alias delete as "del"466467Server.prototype.del = Server.prototype.delete;