http.js
This file
Path
lib/http.js
572 lines · 11.9 KiB · JavaScript
Last changed by
Added support for multiple callbacks for `app.param()`. Closes #801Tj Holowaychukbefore adoptionca75492
History of this fileTake it
The walk stopped after 200 commits: lines older than 0477a53 point at it.
misc refactorTj Holowaychukbefore adoption0477a53
lines 1–14why, 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 = require('./router')Refactored router. Closes #639Tj Holowaychukbefore adoption80e9ffb
line 15why, one step back15 , Router = require('./router')misc refactorTj Holowaychukbefore adoption0477a53
line 16why, one step back16 , view = require('./view')Refactored router. Closes #639Tj Holowaychukbefore adoption80e9ffb
lines 17–18why, one step back17 , toArray = require('./utils').toArray18 , methods = router.methods.concat('del', 'all')Added `app.local(name, val)`Tj Holowaychukbefore adoptionf98896f
line 19why, one step back19 , res = require('./response')misc refactorTj Holowaychukbefore adoption0477a53
lines 20–68why, one step back20 , url = require('url')21 , utils = connect.utils;2223/**24 * Expose `HTTPServer`.25 */2627exports = module.exports = HTTPServer;2829/**30 * Server proto.31 */3233var app = HTTPServer.prototype;3435/**36 * Initialize a new `HTTPServer` with optional `middleware`.37 *38 * @param {Array} middleware39 * @api public40 */4142function HTTPServer(middleware){43 connect.HTTPServer.call(this, []);44 this.init(middleware);45};4647/**48 * Inherit from `connect.HTTPServer`.49 */5051app.__proto__ = connect.HTTPServer.prototype;5253/**54 * Initialize the server.55 *56 * @param {Array} middleware57 * @api private58 */5960app.init = function(middleware){61 var self = this;62 this.cache = {};63 this.settings = {};64 this.redirects = {};65 this.isCallbacks = {};6667 this.set('home', '/');68 this.set('env', process.env.NODE_ENV || 'development');utilize connects new `query()` middlewareTj Holowaychukbefore adoptioneab03fd
line 69why, one step back69 this.use(connect.query());misc refactorTj Holowaychukbefore adoption0477a53
line 70why, one step back70Changed `app.locals` to match `res.locals`Tj Holowaychukbefore adoption1dc8776
lines 71–86why, one step back71 /**72 * Assign several locals with the given `obj`,73 * or return the locals.74 *75 * @param {Object} obj76 * @return {Object|HTTPServer}77 * @api public78 */7980 this.locals = function(obj){81 for (var key in obj) {82 self.locals[key] = obj[key];83 }84 return self;85 };86misc refactorTj Holowaychukbefore adoption0477a53
lines 87–88why, one step back87 // expose objects to each other88 this.use(function(req, res, next){Added "charset" optionTj Holowaychukbefore adoption6ebccb0
line 89why, one step back89 var charset;misc refactorTj Holowaychukbefore adoption0477a53
lines 90–95why, one step back90 req.query = req.query || {};91 res.setHeader('X-Powered-By', 'Express');92 req.app = res.app = self;93 req.res = res;94 res.req = req;95 req.next = next;Added "charset" optionTj Holowaychukbefore adoption6ebccb0
lines 96–99why, one step back9697 // charset98 if (charset = self.set('charset')) res.charset = charset;99Replaced `res.local[s]()` with `res.locals` function. Closes #757Tj Holowaychukbefore adoption9a8b868
lines 100–112why, one step back100 /**101 * Assign several locals with the given `obj`,102 * or return the locals.103 *104 * @param {Object} obj105 * @return {Object|ServerResponse}106 * @api public107 */108109 res.locals = function(obj){110 for (var key in obj) {111 res.locals[key] = obj[key];112 }Changed `app.locals` to match `res.locals`Tj Holowaychukbefore adoption1dc8776
line 113why, one step back113 return res;Replaced `res.local[s]()` with `res.locals` function. Closes #757Tj Holowaychukbefore adoption9a8b868
lines 114–115why, one step back114 };115misc refactorTj Holowaychukbefore adoption0477a53
lines 116–121why, one step back116 next();117 });118119 // apply middleware120 if (middleware) middleware.forEach(self.use.bind(self));121Refactored router. Closes #639Tj Holowaychukbefore adoption80e9ffb
lines 122–123why, one step back122 // router123 this.routes = new Router(this);misc refactorTj Holowaychukbefore adoption0477a53
lines 124–125why, one step back124 this.__defineGetter__('router', function(){125 this.__usedRouter = true;Refactored router. Closes #639Tj Holowaychukbefore adoption80e9ffb
line 126why, one step back126 return self.routes.middleware;misc refactorTj Holowaychukbefore adoption0477a53
lines 127–129why, one step back127 });128129 // default localsRemoved default local "app"Tj Holowaychukbefore adoptiond58beed
line 130why, one step back130 this.locals.settings = this.settings;misc refactorTj Holowaychukbefore adoption0477a53
lines 131–141why, one step back131132 // default development configuration133 this.configure('development', function(){134 this.enable('hints');135 });136137 // default production configuration138 this.configure('production', function(){139 this.enable('view cache');140 });141Refactored router. Closes #639Tj Holowaychukbefore adoption80e9ffb
line 142why, one step back142 // route manipulation methodsmisc refactorTj Holowaychukbefore adoption0477a53
line 143why, one step back143 methods.forEach(function(method){Refactored router. Closes #639Tj Holowaychukbefore adoption80e9ffb
lines 144–145why, one step back144 self.lookup[method] = function(path){145 return self.routes.lookup(method, path);misc refactorTj Holowaychukbefore adoption0477a53
lines 146–147why, one step back146 };147Refactored router. Closes #639Tj Holowaychukbefore adoption80e9ffb
lines 148–149why, one step back148 self.match[method] = function(path){149 return self.routes.match(method, path);misc refactorTj Holowaychukbefore adoption0477a53
lines 150–151why, one step back150 };151Refactored router. Closes #639Tj Holowaychukbefore adoption80e9ffb
lines 152–153why, one step back152 self.remove[method] = function(path){153 return self.routes.lookup(method, path).remove();misc refactorTj Holowaychukbefore adoption0477a53
lines 154–155why, one step back154 };155 });Refactored router. Closes #639Tj Holowaychukbefore adoption80e9ffb
lines 156–160why, one step back156157 // del -> delete158 self.lookup.del = self.lookup.delete;159 self.match.del = self.match.delete;160 self.remove.del = self.remove.delete;misc refactorTj Holowaychukbefore adoption0477a53
lines 161–163why, one step back161};162163/**Refactored router. Closes #639Tj Holowaychukbefore adoption80e9ffb
lines 164–200why, one step back164 * Remove routes matching the given `path`.165 *166 * @param {Route} path167 * @return {Boolean}168 * @api public169 */170171app.remove = function(path){172 return this.routes.lookup('all', path).remove();173};174175/**176 * Lookup routes defined with a path177 * equivalent to `path`.178 *179 * @param {Stirng} path180 * @return {Array}181 * @api public182 */183184app.lookup = function(path){185 return this.routes.lookup('all', path);186};187188/**189 * Lookup routes matching the given `url`.190 *191 * @param {Stirng} url192 * @return {Array}193 * @api public194 */195196app.match = function(url){197 return this.routes.match('all', url);198};199200/**misc refactorTj Holowaychukbefore adoption0477a53
lines 201–285why, one step back201 * 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/**Added support for multiple callbacks for `app.param()`. Closes #801Tj Holowaychukbefore adoptionca75492
line 286why, one step back286<<<<<<< HEADmisc refactorTj Holowaychukbefore adoption0477a53
line 287why, one step back287 * Map the given param placeholder `name`(s) to the given callback `fn`.Added support for multiple callbacks for `app.param()`. Closes #801Tj Holowaychukbefore adoptionca75492
lines 288–290why, one step back288=======289 * Register the given view helpers `obj`. This method290 * can be called several times to apply additional helpers.misc refactorTj Holowaychukbefore adoption0477a53
line 291why, one step back291 *Added support for multiple callbacks for `app.param()`. Closes #801Tj Holowaychukbefore adoptionca75492
lines 292–319why, one step back292 * @param {Object} obj293 * @return {Server} for chaining294 * @api public295 */296297app.helpers =298app.locals = function(obj){299 utils.merge(this._locals, obj);300 return this;301};302303/**304 * Register the given dynamic view helpers `obj`. This method305 * can be called several times to apply additional helpers.306 *307 * @param {Object} obj308 * @return {Server} for chaining309 * @api public310 */311312app.dynamicHelpers = function(obj){313 utils.merge(this.dynamicViewHelpers, obj);314 return this;315};316317/**318 * Map the given param placeholder `name`(s) to the given callback(s).319 *misc refactorTj Holowaychukbefore adoption0477a53
line 320why, one step back320 * Param mapping is used to provide pre-conditions to routesRemoved app.param() callback with retval supportTj Holowaychukbefore adoptione78dc18
lines 321–323why, one step back321 * which us normalized placeholders. This callback has the same322 * signature as regular middleware, for example below when ":userId"323 * is used this function will be invoked in an attempt to load the user.misc refactorTj Holowaychukbefore adoption0477a53
line 324why, one step back324 *docsTj Holowaychukbefore adoption4d12292
lines 325–336why, one step back325 * app.param('userId', function(req, res, next, id){326 * User.find(id, function(err, user){327 * if (err) {328 * next(err);329 * } else if (user) {330 * req.user = user;331 * next();332 * } else {333 * next(new Error('failed to load user'));334 * }335 * });336 * });misc refactorTj Holowaychukbefore adoption0477a53
line 337why, one step back337 *Added support for multiple callbacks for `app.param()`. Closes #801Tj Holowaychukbefore adoptionca75492
lines 338–369why, one step back338 * Passing a single function allows you to map logic339 * to the values passed to `app.param()`, for example340 * this is useful to provide coercion support in a concise manner.341 *342 * The following example maps regular expressions to param values343 * ensuring that they match, otherwise passing control to the next344 * route:345 *346 * app.param(function(name, regexp){347 * if (regexp instanceof RegExp) {348 * return function(req, res, next, val){349 * var captures;350 * if (captures = regexp.exec(String(val))) {351 * req.params[name] = captures;352 * next();353 * } else {354 * next('route');355 * }356 * }357 * }358 * });359 *360 * We can now use it as shown below, where "/commit/:commit" expects361 * that the value for ":commit" is at 5 or more digits. The capture362 * groups are then available as `req.params.commit` as we defined363 * in the function above.364 *365 * app.param('commit', /^\d{5,}$/);366 *367 * For more of this useful functionality take a look368 * at [express-params](http://github.com/visionmedia/express-params).369 *Added support for app.param(fn) to define param logicTj Holowaychukbefore adoptionb1a7310
line 370why, one step back370 * @param {String|Array|Function} namemisc refactorTj Holowaychukbefore adoption0477a53
lines 371–376why, one step back371 * @param {Function} fn372 * @return {Server} for chaining373 * @api public374 */375376app.param = function(name, fn){Added support for multiple callbacks for `app.param()`. Closes #801Tj Holowaychukbefore adoptionca75492
lines 377–379why, one step back377 var self = this378 , fns = [].slice.call(arguments, 1);379Added support for app.param(fn) to define param logicTj Holowaychukbefore adoptionb1a7310
line 380why, one step back380 // arraymisc refactorTj Holowaychukbefore adoption0477a53
lines 381–382why, one step back381 if (Array.isArray(name)) {382 name.forEach(function(name){Added support for multiple callbacks for `app.param()`. Closes #801Tj Holowaychukbefore adoptionca75492
lines 383–386why, one step back383 fns.forEach(function(fn){384 self.param(name, fn);385 });386 });Added support for app.param(fn) to define param logicTj Holowaychukbefore adoptionb1a7310
lines 387–390why, one step back387 // param logic388 } else if ('function' == typeof name) {389 this.routes.param(name);390 // singlemisc refactorTj Holowaychukbefore adoption0477a53
lines 391–392why, one step back391 } else {392 if (':' == name[0]) name = name.substr(1);Added support for multiple callbacks for `app.param()`. Closes #801Tj Holowaychukbefore adoptionca75492
lines 393–395why, one step back393 fns.forEach(function(fn){394 self.routes.param(name, fn);395 });misc refactorTj Holowaychukbefore adoption0477a53
line 396why, one step back396 }Added support for app.param(fn) to define param logicTj Holowaychukbefore adoptionb1a7310
line 397why, one step back397misc refactorTj Holowaychukbefore adoption0477a53
lines 398–501why, one step back398 return this;399};400401/**402 * Register the given callback `fn` for the given `type`.403 *404 * @param {String} type405 * @param {Function} fn406 * @return {Server} for chaining407 * @api public408 */409410app.is = function(type, fn){411 if (!fn) return this.isCallbacks[type];412 this.isCallbacks[type] = fn;413 return this;414};415416/**417 * Assign `setting` to `val`, or return `setting`'s value.418 * Mounted servers inherit their parent server's settings.419 *420 * @param {String} setting421 * @param {String} val422 * @return {Server|Mixed} for chaining, or the setting value423 * @api public424 */425426app.set = function(setting, val){427 if (val === undefined) {428 if (this.settings.hasOwnProperty(setting)) {429 return this.settings[setting];430 } else if (this.parent) {431 return this.parent.set(setting);432 }433 } else {434 this.settings[setting] = val;435 return this;436 }437};438439/**440 * Check if `setting` is enabled.441 *442 * @param {String} setting443 * @return {Boolean}444 * @api public445 */446447app.enabled = function(setting){448 return !!this.set(setting);449};450451/**452 * Check if `setting` is disabled.453 *454 * @param {String} setting455 * @return {Boolean}456 * @api public457 */458459app.disabled = function(setting){460 return !this.set(setting);461};462463/**464 * Enable `setting`.465 *466 * @param {String} setting467 * @return {Server} for chaining468 * @api public469 */470471app.enable = function(setting){472 return this.set(setting, true);473};474475/**476 * Disable `setting`.477 *478 * @param {String} setting479 * @return {Server} for chaining480 * @api public481 */482483app.disable = function(setting){484 return this.set(setting, false);485};486487/**488 * Redirect `key` to `url`.489 *490 * @param {String} key491 * @param {String} url492 * @return {Server} for chaining493 * @api public494 */495496app.redirect = function(key, url){497 this.redirects[key] = url;498 return this;499};500501/**docsTj Holowaychukbefore adoptionf46ae9f
lines 502–505why, one step back502 * Configure callback for zero or more envs,503 * when no env is specified that callback will504 * be invoked for all environments. Any combination505 * can be used multiple times, in any order desired.misc refactorTj Holowaychukbefore adoption0477a53
line 506why, one step back506 *Added support for multiple env app.configure() calls. Closes #735Tj Holowaychukbefore adoption9f2b344
lines 507–521why, one step back507 * Examples:508 *509 * app.configure(function(){510 * // executed for all envs511 * });512 *513 * app.configure('stage', function(){514 * // executed staging env515 * });516 *517 * app.configure('stage', 'production', function(){518 * // executed for stage and production519 * });520 *521 * @param {String} env...misc refactorTj Holowaychukbefore adoption0477a53
lines 522–527why, one step back522 * @param {Function} fn523 * @return {Server} for chaining524 * @api public525 */526527app.configure = function(env, fn){Added support for multiple env app.configure() calls. Closes #735Tj Holowaychukbefore adoption9f2b344
lines 528–532why, one step back528 var envs = 'all'529 , args = toArray(arguments);530 fn = args.pop();531 if (args.length) envs = args;532 if ('all' == envs || ~envs.indexOf(this.settings.env)) fn.call(this);misc refactorTj Holowaychukbefore adoption0477a53
lines 533–535why, one step back533 return this;534};535Refactored router. Closes #639Tj Holowaychukbefore adoption80e9ffb
lines 536–538why, one step back536/**537 * Delegate `.VERB(...)` calls to `.route(VERB, ...)`.538 */misc refactorTj Holowaychukbefore adoption0477a53
lines 539–541why, one step back539540methods.forEach(function(method){541 app[method] = function(path){Refactored router. Closes #639Tj Holowaychukbefore adoption80e9ffb
lines 542–543why, one step back542 if (1 == arguments.length) return this.routes.lookup(method, path);543 var args = [method].concat(toArray(arguments));misc refactorTj Holowaychukbefore adoption0477a53
line 544why, one step back544 if (!this.__usedRouter) this.use(this.router);Refactored router. Closes #639Tj Holowaychukbefore adoption80e9ffb
lines 545–546why, one step back545 return this.routes._route.apply(this.routes, args);546 }misc refactorTj Holowaychukbefore adoption0477a53
lines 547–548why, one step back547});548Refactored router. Closes #639Tj Holowaychukbefore adoption80e9ffb
lines 549–557why, one step back549/**550 * Special-cased "all" method, applying the given route `path`,551 * middleware, and callback to _every_ HTTP method.552 *553 * @param {String} path554 * @param {Function} ...555 * @return {Server} for chaining556 * @api public557 */misc refactorTj Holowaychukbefore adoption0477a53
line 558why, one step back558Refactored router. Closes #639Tj Holowaychukbefore adoption80e9ffb
lines 559–570why, one step back559app.all = function(path){560 var args = arguments;561 if (1 == args.length) return this.routes.lookup('all', path);562 methods.forEach(function(method){563 if ('all' == method) return;564 app[method].apply(this, args);565 }, this);566 return this;567};568569// del -> delete alias570misc refactorTj Holowaychukbefore adoption0477a53
line 571why, one step back571app.del = app.delete;Refactored router. Closes #639Tj Holowaychukbefore adoption80e9ffb
line 572why, one step back572