Skip to content
Myr

http.js

This file

Path

lib/http.js

494 lines · 10.5 KiB · JavaScript

Last changed by

viewHelpers -> _localsTj Holowaychukbefore adoptioneac6665

History of this file

Take it

The walk stopped after 200 commits: lines older than 0800141 point at it.

semi-colonsTj Holowaychukbefore adoption0800141

lines 1–46why, one step back
1
2/*!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;

Merge branch 'feature/route-lookup'Tj Holowaychukbefore adoption260d03a

lines 47–48why, one step back
47 this.match = {};
48 this.lookup = {};

semi-colonsTj Holowaychukbefore adoption0800141

lines 49–51why, one step back
49 this.settings = {};
50 this.redirects = {};51 this.isCallbacks = {};

viewHelpers -> _localsTj Holowaychukbefore adoptioneac6665

line 52why, one step back
52 this._locals = {};

semi-colonsTj Holowaychukbefore adoption0800141

lines 53–55why, one step back
53 this.dynamicViewHelpers = {};
54 this.errorHandlers = [];55

Merge branch 'integration'Tj Holowaychukbefore adoptionf3c068a

line 56why, one step back
56 // default "home" to /

semi-colonsTj Holowaychukbefore adoption0800141

lines 57–64why, one step back
57 this.set('home', '/');
5859 // set "env" to NODE_ENV, defaulting to "development"60 this.set('env', process.env.NODE_ENV || 'development');6162 // expose objects to each other63 this.use(function(req, res, next){64 req.query = req.query || {};

refactored res.send()Tj Holowaychukbefore adoption3661922

line 65why, one step back
65 res.setHeader('X-Powered-By', 'Express');

semi-colonsTj Holowaychukbefore adoption0800141

lines 66–87why, one step back
66 req.app = res.app = self;
67 req.res = res;68 res.req = req;69 req.next = next;70 // assign req.query71 if (req.url.indexOf('?') > 0) {72 var query = url.parse(req.url).query;73 req.query = qs.parse(query);74 }75 next();76 });7778 // apply middleware79 if (middleware) middleware.forEach(self.use.bind(self));8081 // use router, expose as app.get(), etc82 var fn = router(function(app){ self.routes = app; });83 this.__defineGetter__('router', function(){84 this.__usedRouter = true;85 return fn;86 });87

Added 'settings' local variable, containing the app's settingsTj Holowaychukbefore adoption9d2bd29

line 88why, one step back
88 // default locals

Added "request", "response", and "app" localsTj Holowaychukbefore adoption319fbf7

lines 89–93why, one step back
89 this.locals({
90 settings: this.settings91 , app: this92 });93

Added view resolution hints when in developmentTj Holowaychukbefore adoptionf1f1261

lines 94–98why, one step back
94 // default development configuration
95 this.configure('development', function(){96 this.enable('hints');97 });98

semi-colonsTj Holowaychukbefore adoption0800141

lines 99–100why, one step back
99 // default production configuration
100 this.configure('production', function(){

Renamed "cache views" to "view cache". Closes #628Tj Holowaychukbefore adoptiond9e7153

line 101why, one step back
101 this.enable('view cache');

semi-colonsTj Holowaychukbefore adoption0800141

lines 102–106why, one step back
102 });
103104 // register error handlers on "listening"105 // so that they disregard definition position.106 this.on('listening', this.registerErrorHandlers.bind(this));

Merge branch 'feature/route-lookup'Tj Holowaychukbefore adoption260d03a

lines 107–121why, one step back
107
108 // route lookup methods109 methods.forEach(function(method){110 self.match[method] = function(url){111 return self.router.match(url, 'all' == method112 ? null113 : method);114 };115116 self.lookup[method] = function(path){117 return self.router.lookup(path, 'all' == method118 ? null119 : method);120 };121 });

semi-colonsTj Holowaychukbefore adoption0800141

lines 122–158why, one step back
122};
123124/**125 * When using the vhost() middleware register error handlers.126 */127128Server.prototype.onvhost = function(){129 this.registerErrorHandlers();130};131132/**133 * Register error handlers.134 *135 * @return {Server} for chaining136 * @api public137 */138139Server.prototype.registerErrorHandlers = function(){140 this.errorHandlers.forEach(function(fn){141 this.use(function(err, req, res, next){142 fn.apply(this, arguments);143 });144 }, this);145 return this;146};147148/**149 * Proxy `connect.HTTPServer#use()` to apply settings to150 * mounted applications.151 *152 * @param {String|Function|Server} route153 * @param {Function|Server} middleware154 * @return {Server} for chaining155 * @api public156 */157158Server.prototype.use = function(route, middleware){

Merge branch 'integration'Tj Holowaychukbefore adoptionf3c068a

line 159why, one step back
159 var app, home, handle;

Fixed mounting of non-express serversTj Holowaychukbefore adoption2dae6d8

line 160why, one step back
160

semi-colonsTj Holowaychukbefore adoption0800141

lines 161–164why, one step back
161 if ('string' != typeof route) {
162 middleware = route, route = '/';163 }164

Merge branch 'integration'Tj Holowaychukbefore adoptionf3c068a

lines 165–179why, one step back
165 // express app
166 if (middleware.handle && middleware.set) app = middleware;167168 // restore .app property on req and res169 if (app) {170 app.route = route;171 middleware = function(req, res, next) {172 var orig = req.app;173 app.handle(req, res, function(err){174 req.app = res.app = orig;175 next(err);176 });177 };178 }179

semi-colonsTj Holowaychukbefore adoption0800141

lines 180–181why, one step back
180 connect.HTTPServer.prototype.use.call(this, route, middleware);
181

Merge branch 'integration'Tj Holowaychukbefore adoptionf3c068a

lines 182–188why, one step back
182 // mounted an app, invoke the hook
183 // and adjust some settings184 if (app) {185 home = app.set('home');186 if ('/' == home) home = '';187 app.set('home', app.route + home);188 app.parent = this;

semi-colonsTj Holowaychukbefore adoption0800141

lines 189–241why, one step back
189 if (app.__mounted) app.__mounted.call(app, this);
190 }191192 return this;193};194195/**196 * Assign a callback `fn` which is called197 * when this `Server` is passed to `Server#use()`.198 *199 * Examples:200 *201 * var app = express.createServer()202 * , blog = express.createServer();203 *204 * blog.mounted(function(parent){205 * // parent is app206 * // "this" is blog207 * });208 *209 * app.use(blog);210 *211 * @param {Function} fn212 * @return {Server} for chaining213 * @api public214 */215216Server.prototype.mounted = function(fn){217 this.__mounted = fn;218 return this;219};220221/**222 * See: view.register.223 *224 * @return {Server} for chaining225 * @api public226 */227228Server.prototype.register = function(){229 view.register.apply(this, arguments);230 return this;231};232233/**234 * Register the given view helpers `obj`. This method235 * can be called several times to apply additional helpers.236 *237 * @param {Object} obj238 * @return {Server} for chaining239 * @api public240 */241

Merge branch 'integration'Tj Holowaychukbefore adoptionf3c068a

line 242why, one step back
242Server.prototype.helpers =

semi-colonsTj Holowaychukbefore adoption0800141

line 243why, one step back
243Server.prototype.locals = function(obj){

viewHelpers -> _localsTj Holowaychukbefore adoptioneac6665

line 244why, one step back
244 utils.merge(this._locals, obj);

semi-colonsTj Holowaychukbefore adoption0800141

lines 245–266why, one step back
245 return this;
246};247248/**249 * Register the given dynamic view helpers `obj`. This method250 * can be called several times to apply additional helpers.251 *252 * @param {Object} obj253 * @return {Server} for chaining254 * @api public255 */256257Server.prototype.dynamicHelpers = function(obj){258 utils.merge(this.dynamicViewHelpers, obj);259 return this;260};261262/**263 * Map the given param placeholder `name`(s) to the given callback `fn`.264 *265 * Param mapping is used to provide pre-conditions to routes266 * which us normalized placeholders. For example ":user_id" may

Merge branch 'integration'Tj Holowaychukbefore adoptionf3c068a

line 267why, one step back
267 * attempt to load the user from the database, where as ":num" may

semi-colonsTj Holowaychukbefore adoption0800141

lines 268–275why, one step back
268 * pass the value through `parseInt(num, 10)`.
269 *270 * When the callback function accepts only a single argument, the271 * value of placeholder is passed:272 *273 * app.param('page', function(n){ return parseInt(n, 10); });274 *275 * After which "/users/:page" would automatically provide us with

Merge branch 'integration'Tj Holowaychukbefore adoptionf3c068a

line 276why, one step back
276 * an integer for `req.params.page`. If desired we could use the callback

semi-colonsTj Holowaychukbefore adoption0800141

lines 277–454why, one step back
277 * signature shown below, and immediately `next(new Error('invalid page'))`
278 * when `parseInt` fails.279 *280 * Alternatively the callback may accept the request, response, next, and281 * the value, acting like middlware:282 *283 * app.param('userId', function(req, res, next, id){284 * User.find(id, function(err, user){285 * if (err) {286 * next(err);287 * } else if (user) {288 * req.user = user;289 * next();290 * } else {291 * next(new Error('failed to load user'));292 * }293 * });294 * });295 *296 * Now every time ":userId" is present, the associated user object297 * will be loaded and assigned before the route handler is invoked.298 *299 * @param {String|Array} name300 * @param {Function} fn301 * @return {Server} for chaining302 * @api public303 */304305Server.prototype.param = function(name, fn){306 if (Array.isArray(name)) {307 name.forEach(function(name){308 this.param(name, fn);309 }, this);310 } else {311 if (':' == name[0]) name = name.substr(1);312 this.routes.param(name, fn);313 }314 return this;315};316317/**318 * Assign a custom exception handler callback `fn`.319 * These handlers are always _last_ in the middleware stack.320 *321 * @param {Function} fn322 * @return {Server} for chaining323 * @api public324 */325326Server.prototype.error = function(fn){327 this.errorHandlers.push(fn);328 return this;329};330331/**332 * Register the given callback `fn` for the given `type`.333 *334 * @param {String} type335 * @param {Function} fn336 * @return {Server} for chaining337 * @api public338 */339340Server.prototype.is = function(type, fn){341 if (!fn) return this.isCallbacks[type];342 this.isCallbacks[type] = fn;343 return this;344};345346/**347 * Assign `setting` to `val`, or return `setting`'s value.348 * Mounted servers inherit their parent server's settings.349 *350 * @param {String} setting351 * @param {String} val352 * @return {Server|Mixed} for chaining, or the setting value353 * @api public354 */355356Server.prototype.set = function(setting, val){357 if (val === undefined) {358 if (this.settings.hasOwnProperty(setting)) {359 return this.settings[setting];360 } else if (this.parent) {361 return this.parent.set(setting);362 }363 } else {364 this.settings[setting] = val;365 return this;366 }367};368369/**370 * Check if `setting` is enabled.371 *372 * @param {String} setting373 * @return {Boolean}374 * @api public375 */376377Server.prototype.enabled = function(setting){378 return !!this.set(setting);379};380381/**382 * Check if `setting` is disabled.383 *384 * @param {String} setting385 * @return {Boolean}386 * @api public387 */388389Server.prototype.disabled = function(setting){390 return !this.set(setting);391};392393/**394 * Enable `setting`.395 *396 * @param {String} setting397 * @return {Server} for chaining398 * @api public399 */400401Server.prototype.enable = function(setting){402 return this.set(setting, true);403};404405/**406 * Disable `setting`.407 *408 * @param {String} setting409 * @return {Server} for chaining410 * @api public411 */412413Server.prototype.disable = function(setting){414 return this.set(setting, false);415};416417/**418 * Redirect `key` to `url`.419 *420 * @param {String} key421 * @param {String} url422 * @return {Server} for chaining423 * @api public424 */425426Server.prototype.redirect = function(key, url){427 this.redirects[key] = url;428 return this;429};430431/**432 * Configure callback for the given `env`.433 *434 * @param {String} env435 * @param {Function} fn436 * @return {Server} for chaining437 * @api public438 */439440Server.prototype.configure = function(env, fn){441 if ('function' == typeof env) {442 fn = env, env = 'all';443 }444 if ('all' == env || env == this.settings.env) {445 fn.call(this);446 }447 return this;448};449450// Generate routing methods451452function generateMethod(method){453 Server.prototype[method] = function(path, fn){454 var self = this;

Merge branch 'feature/route-lookup'Tj Holowaychukbefore adoption260d03a

lines 455–461why, one step back
455
456 // Lookup457 if (1 == arguments.length) {458 return this.router.lookup(path, 'all' == method459 ? null460 : method);461 }

semi-colonsTj Holowaychukbefore adoption0800141

lines 462–494why, one step back
462
463 // Ensure router is mounted464 if (!this.__usedRouter) {465 this.use(this.router);466 }467468 // Route specific middleware support469 if (arguments.length > 2) {470 var args = Array.prototype.slice.call(arguments, 1);471 fn = args.pop();472 (function stack(middleware){473 middleware.forEach(function(fn){474 if (Array.isArray(fn)) {475 stack(fn);476 } else {477 self[method](path, fn);478 }479 });480 })(args);481 }482483 // Generate the route484 this.routes[method](path, fn);485 return this;486 };487 return arguments.callee;488}489490methods.forEach(generateMethod);491492// Alias delete as "del"493494Server.prototype.del = Server.prototype.delete;