Skip to content
Myr

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 file

Take it

Merge branch 'features/https'Tj Holowaychukbefore adoption8261437

lines 1–53why, 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;47 this.settings = {};48 this.redirects = {};49 this.isCallbacks = {};50 this.viewHelpers = {};51 this.dynamicViewHelpers = {};52 this.errorHandlers = [];53

Merge branch 'integration'Tj Holowaychukbefore adoptionf3c068a

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

Merge branch 'features/https'Tj Holowaychukbefore adoption8261437

lines 55–56why, one step back
55 this.set('home', '/');
56

docsTj Holowaychukbefore adoption41467d5

line 57why, one step back
57 // set "env" to NODE_ENV, defaulting to "development"

Merge branch 'features/https'Tj Holowaychukbefore adoption8261437

lines 58–59why, one step back
58 this.set('env', process.env.NODE_ENV || 'development');
59

docsTj Holowaychukbefore adoption41467d5

line 60why, one step back
60 // expose objects to each other

Merge branch 'features/https'Tj Holowaychukbefore adoption8261437

lines 61–62why, one step back
61 this.use(function(req, res, next){
62 req.query = req.query || {};

refactored res.send()Tj Holowaychukbefore adoption3661922

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

Merge branch 'features/https'Tj Holowaychukbefore adoption8261437

lines 64–67why, one step back
64 req.app = res.app = self;
65 req.res = res;66 res.req = req;67 req.next = next;

docsTj Holowaychukbefore adoption41467d5

line 68why, one step back
68 // assign req.query

Merge branch 'features/https'Tj Holowaychukbefore adoption8261437

lines 69–75why, one step back
69 if (req.url.indexOf('?') > 0) {
70 var query = url.parse(req.url).query;71 req.query = qs.parse(query);72 }73 next();74 });75

docsTj Holowaychukbefore adoption41467d5

line 76why, one step back
76 // apply middleware

misc refactoringTj Holowaychukbefore adoption5ec4ea7

line 77why, one step back
77 if (middleware) middleware.forEach(self.use.bind(self));

Merge branch 'features/https'Tj Holowaychukbefore adoption8261437

line 78why, one step back
78

docsTj Holowaychukbefore adoption41467d5

line 79why, one step back
79 // use router, expose as app.get(), etc

Merge branch 'features/https'Tj Holowaychukbefore adoption8261437

lines 80–85why, one step back
80 var fn = router(function(app){ self.routes = app; });
81 this.__defineGetter__('router', function(){82 this.__usedRouter = true;83 return fn;84 });85

Added view resolution hints when in developmentTj Holowaychukbefore adoptionf1f1261

lines 86–90why, one step back
86 // default development configuration
87 this.configure('development', function(){88 this.enable('hints');89 });90

docsTj Holowaychukbefore adoption41467d5

line 91why, one step back
91 // default production configuration

Merge branch 'features/https'Tj Holowaychukbefore adoption8261437

lines 92–95why, one step back
92 this.configure('production', function(){
93 this.enable('cache views');94 });95

refactor errorHandler registrationTj Holowaychukbefore adoption8480869

lines 96–98why, one step back
96 // register error handlers on "listening"
97 // so that they disregard definition position.98 this.on('listening', this.registerErrorHandlers.bind(this));

Merge branch 'features/https'Tj Holowaychukbefore adoption8261437

lines 99–109why, one step back
99};
100101/**102 * When using the vhost() middleware register error handlers.103 */104105Server.prototype.onvhost = function(){106 this.registerErrorHandlers();107};108109/**

refactor errorHandler registrationTj Holowaychukbefore adoption8480869

line 110why, one step back
110 * Register error handlers.

Merge branch 'features/https'Tj Holowaychukbefore adoption8261437

lines 111–135why, one step back
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){

Merge branch 'integration'Tj Holowaychukbefore adoptionf3c068a

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

Fixed mounting of non-express serversTj Holowaychukbefore adoption2dae6d8

line 137why, one step back
137

misc refactoringTj Holowaychukbefore adoption7c15cde

line 138why, one step back
138 if ('string' != typeof route) {

Merge branch 'features/https'Tj Holowaychukbefore adoption8261437

lines 139–141why, one step back
139 middleware = route, route = '/';
140 }141

Merge branch 'integration'Tj Holowaychukbefore adoptionf3c068a

lines 142–156why, one step back
142 // express app
143 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 }156

Merge branch 'features/https'Tj Holowaychukbefore adoption8261437

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

Merge branch 'integration'Tj Holowaychukbefore adoptionf3c068a

lines 159–165why, one step back
159 // mounted an app, invoke the hook
160 // 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;

Merge branch 'features/https'Tj Holowaychukbefore adoption8261437

lines 166–177why, one step back
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 *

misc refactoringTj Holowaychukbefore adoption7c15cde

lines 178–179why, one step back
178 * var app = express.createServer()
179 * , blog = express.createServer();

Merge branch 'features/https'Tj Holowaychukbefore adoption8261437

lines 180–181why, one step back
180 *
181 * blog.mounted(function(parent){

misc refactoringTj Holowaychukbefore adoption7c15cde

lines 182–183why, one step back
182 * // parent is app
183 * // "this" is blog

Merge branch 'features/https'Tj Holowaychukbefore adoption8261437

lines 184–218why, one step back
184 * });
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 */218

Merge branch 'integration'Tj Holowaychukbefore adoptionf3c068a

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

Merge branch 'features/https'Tj Holowaychukbefore adoption8261437

lines 220–243why, one step back
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" may

Merge branch 'integration'Tj Holowaychukbefore adoptionf3c068a

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

Merge branch 'features/https'Tj Holowaychukbefore adoption8261437

lines 245–252why, one step back
245 * 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 with

Merge branch 'integration'Tj Holowaychukbefore adoptionf3c068a

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

Merge branch 'features/https'Tj Holowaychukbefore adoption8261437

lines 254–259why, one step back
254 * 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 *

misc refactoringTj Holowaychukbefore adoption7c15cde

lines 260–271why, one step back
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 * });

Merge branch 'features/https'Tj Holowaychukbefore adoption8261437

lines 272–417why, one step back
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){

misc refactoringTj Holowaychukbefore adoption7c15cde

line 418why, one step back
418 if ('function' == typeof env) {

Merge branch 'features/https'Tj Holowaychukbefore adoption8261437

lines 419–464why, one step back
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;