Skip to content
Myr

http.js

This file

Path

lib/http.js

453 lines · 9.6 KiB · JavaScript

Last changed by

Added view resolution hints when in developmentTj Holowaychukbefore adoptionf1f1261

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

docsTj Holowaychukbefore adoption41467d5

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){

Fixed mounting of non-express serversTj Holowaychukbefore adoption2dae6d8

lines 136–137why, one step back
136 var app, home;
137

misc refactoringTj Holowaychukbefore adoption7c15cde

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

Merge branch 'features/https'Tj Holowaychukbefore adoption8261437

lines 139–143why, one step back
139 middleware = route, route = '/';
140 }141142 connect.HTTPServer.prototype.use.call(this, route, middleware);143

misc refactoringTj Holowaychukbefore adoption7c15cde

lines 144–145why, one step back
144 // mounted an app
145 if (middleware.handle) {

Fixed mounting of non-express serversTj Holowaychukbefore adoption2dae6d8

lines 146–153why, one step back
146 app = middleware;
147 // express app148 if (app.set) {149 home = app.set('home');150 if ('/' == home) home = '';151 app.set('home', app.route + home);152 app.parent = this;153 }

misc refactoringTj Holowaychukbefore adoption7c15cde

line 154why, one step back
154 // mounted hook

Merge branch 'features/https'Tj Holowaychukbefore adoption8261437

lines 155–166why, one step back
155 if (app.__mounted) app.__mounted.call(app, this);
156 }157158 return this;159};160161/**162 * Assign a callback `fn` which is called163 * when this `Server` is passed to `Server#use()`.164 *165 * Examples:166 *

misc refactoringTj Holowaychukbefore adoption7c15cde

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

Merge branch 'features/https'Tj Holowaychukbefore adoption8261437

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

misc refactoringTj Holowaychukbefore adoption7c15cde

lines 171–172why, one step back
171 * // parent is app
172 * // "this" is blog

Merge branch 'features/https'Tj Holowaychukbefore adoption8261437

lines 173–248why, one step back
173 * });
174 *175 * app.use(blog);176 *177 * @param {Function} fn178 * @return {Server} for chaining179 * @api public180 */181182Server.prototype.mounted = function(fn){183 this.__mounted = fn;184 return this;185};186187/**188 * See: view.register.189 *190 * @return {Server} for chaining191 * @api public192 */193194Server.prototype.register = function(){195 view.register.apply(this, arguments);196 return this;197};198199/**200 * Register the given view helpers `obj`. This method201 * can be called several times to apply additional helpers.202 *203 * @param {Object} obj204 * @return {Server} for chaining205 * @api public206 */207208Server.prototype.helpers = 209Server.prototype.locals = function(obj){210 utils.merge(this.viewHelpers, obj);211 return this;212};213214/**215 * Register the given dynamic view helpers `obj`. This method216 * can be called several times to apply additional helpers.217 *218 * @param {Object} obj219 * @return {Server} for chaining220 * @api public221 */222223Server.prototype.dynamicHelpers = function(obj){224 utils.merge(this.dynamicViewHelpers, obj);225 return this;226};227228/**229 * Map the given param placeholder `name`(s) to the given callback `fn`.230 *231 * Param mapping is used to provide pre-conditions to routes232 * which us normalized placeholders. For example ":user_id" may233 * attempt to load the user from the database, where as ":num" may 234 * pass the value through `parseInt(num, 10)`.235 *236 * When the callback function accepts only a single argument, the237 * value of placeholder is passed:238 *239 * app.param('page', function(n){ return parseInt(n, 10); });240 *241 * After which "/users/:page" would automatically provide us with242 * an integer for `req.params.page`. If desired we could use the callback 243 * signature shown below, and immediately `next(new Error('invalid page'))`244 * when `parseInt` fails.245 *246 * Alternatively the callback may accept the request, response, next, and247 * the value, acting like middlware:248 *

misc refactoringTj Holowaychukbefore adoption7c15cde

lines 249–260why, one step back
249 * app.param('userId', function(req, res, next, id){
250 * User.find(id, function(err, user){251 * if (err) {252 * next(err);253 * } else if (user) {254 * req.user = user;255 * next();256 * } else {257 * next(new Error('failed to load user'));258 * }259 * });260 * });

Merge branch 'features/https'Tj Holowaychukbefore adoption8261437

lines 261–406why, one step back
261 *
262 * Now every time ":userId" is present, the associated user object263 * will be loaded and assigned before the route handler is invoked.264 *265 * @param {String|Array} name266 * @param {Function} fn267 * @return {Server} for chaining268 * @api public269 */270271Server.prototype.param = function(name, fn){272 if (Array.isArray(name)) {273 name.forEach(function(name){274 this.param(name, fn);275 }, this);276 } else {277 if (':' == name[0]) name = name.substr(1);278 this.routes.param(name, fn);279 }280 return this;281};282283/**284 * Assign a custom exception handler callback `fn`.285 * These handlers are always _last_ in the middleware stack.286 *287 * @param {Function} fn288 * @return {Server} for chaining289 * @api public290 */291292Server.prototype.error = function(fn){293 this.errorHandlers.push(fn);294 return this;295};296297/**298 * Register the given callback `fn` for the given `type`.299 *300 * @param {String} type301 * @param {Function} fn302 * @return {Server} for chaining303 * @api public304 */305306Server.prototype.is = function(type, fn){307 if (!fn) return this.isCallbacks[type];308 this.isCallbacks[type] = fn;309 return this;310};311312/**313 * Assign `setting` to `val`, or return `setting`'s value.314 * Mounted servers inherit their parent server's settings.315 *316 * @param {String} setting317 * @param {String} val318 * @return {Server|Mixed} for chaining, or the setting value319 * @api public320 */321322Server.prototype.set = function(setting, val){323 if (val === undefined) {324 if (this.settings.hasOwnProperty(setting)) {325 return this.settings[setting];326 } else if (this.parent) {327 return this.parent.set(setting);328 }329 } else {330 this.settings[setting] = val;331 return this;332 }333};334335/**336 * Check if `setting` is enabled.337 *338 * @param {String} setting339 * @return {Boolean}340 * @api public341 */342343Server.prototype.enabled = function(setting){344 return !!this.set(setting);345};346347/**348 * Check if `setting` is disabled.349 *350 * @param {String} setting351 * @return {Boolean}352 * @api public353 */354355Server.prototype.disabled = function(setting){356 return !this.set(setting);357};358359/**360 * Enable `setting`.361 *362 * @param {String} setting363 * @return {Server} for chaining364 * @api public365 */366367Server.prototype.enable = function(setting){368 return this.set(setting, true);369};370371/**372 * Disable `setting`.373 *374 * @param {String} setting375 * @return {Server} for chaining376 * @api public377 */378379Server.prototype.disable = function(setting){380 return this.set(setting, false);381};382383/**384 * Redirect `key` to `url`.385 *386 * @param {String} key387 * @param {String} url388 * @return {Server} for chaining389 * @api public390 */391392Server.prototype.redirect = function(key, url){393 this.redirects[key] = url;394 return this;395};396397/**398 * Configure callback for the given `env`.399 *400 * @param {String} env401 * @param {Function} fn402 * @return {Server} for chaining403 * @api public404 */405406Server.prototype.configure = function(env, fn){

misc refactoringTj Holowaychukbefore adoption7c15cde

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

Merge branch 'features/https'Tj Holowaychukbefore adoption8261437

lines 408–453why, one step back
408 fn = env, env = 'all';
409 }410 if ('all' == env || env == this.settings.env) {411 fn.call(this);412 }413 return this;414};415416// Generate routing methods417418function generateMethod(method){419 Server.prototype[method] = function(path, fn){420 var self = this;421422 // Ensure router is mounted423 if (!this.__usedRouter) {424 this.use(this.router);425 }426427 // Route specific middleware support428 if (arguments.length > 2) {429 var args = Array.prototype.slice.call(arguments, 1);430 fn = args.pop();431 (function stack(middleware){432 middleware.forEach(function(fn){433 if (Array.isArray(fn)) {434 stack(fn);435 } else {436 self[method](path, fn);437 }438 });439 })(args);440 }441442 // Generate the route443 this.routes[method](path, fn);444 return this;445 };446 return arguments.callee;447}448449methods.forEach(generateMethod);450451// Alias delete as "del"452453Server.prototype.del = Server.prototype.delete;