Moved server.js into http.js
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Tj Holowaychuk · committed by Tj Holowaychuk · parent cd519e9 · Browse files · 5 files·+464 added−464 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
5 files+464 added−464 removed
- tests:+2 added−2 removed
- other:+462 added−462 removed
Provenance
- Commit
da7921f- Tree
4d15ddd- Author
Tj Holowaychuk <tj@vision-media.ca>- Committer
Tj Holowaychuk <tj@vision-media.ca>- Parent
cd519e9
5 files changed+464 added−464 removed
modified:lib/express.js+4 added-4 removed
8 unmodified lines910111213131415161718 unmodified lines3637383940404142434444454647474849505114 unmodified lines8 unmodified lines * Module dependencies. */
var connect = require('connect') , Server = require('./server'); , HTTPServer = require('./http');
/** * Re-export connect auto-loaders. * 18 unmodified lines * @api public */
exports.createServer = function(){ return new Server(Array.prototype.slice.call(arguments)); return new HTTPServer(Array.prototype.slice.call(arguments));};
/** * Expose `Server`. * Expose `HTTPServer`. */
exports.Server = Server;exports.HTTPServer = HTTPServer;
/** * View extensions. */14 unmodified linesadded:lib/http.js+458 added
1+2+/*!3+ * Express - HTTPServer4+ * Copyright(c) 2010 TJ Holowaychuk <tj@vision-media.ca>5+ * MIT Licensed6+ */7+8+/**9+ * Module dependencies.10+ */11+12+var queryString = require('querystring')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;19+20+/**21+ * Initialize a new `Server` with optional `middleware`.22+ *23+ * @param {Array} middleware24+ * @api public25+ */26+27+var Server = exports = module.exports = function HTTPServer(middleware){28+ var self = this;29+ this.settings = {};30+ this.redirects = {};31+ this.isCallbacks = {};32+ this.viewHelpers = {};33+ this.dynamicViewHelpers = {};34+ this.errorHandlers = [];35+ connect.HTTPServer.call(this, []);36+37+ // Default "home" to / 38+ this.set('home', '/');39+40+ // Set "env" to NODE_ENV, defaulting to "development"41+ this.set('env', process.env.NODE_ENV || 'development');42+43+ // Expose objects to each other44+ this.use(function(req, res, next){45+ req.query = req.query || {};46+ res.headers = { 'X-Powered-By': 'Express' };47+ req.app = res.app = self;48+ req.res = res;49+ res.req = req;50+ req.next = next;51+ // Assign req.params.get52+ if (req.url.indexOf('?') > 0) {53+ var query = url.parse(req.url).query;54+ req.query = exports.parseQueryString(query);55+ }56+ next();57+ });58+59+ // Apply middleware60+ if (middleware) {61+ middleware.forEach(function(fn){62+ self.use(fn);63+ });64+ }65+66+ // Use router, expose as app.get(), etc67+ var fn = router(function(app){ self.routes = app; });68+ this.__defineGetter__('router', function(){69+ this.__usedRouter = true;70+ return fn;71+ });72+73+ // Default production configuration74+ this.configure('production', function(){75+ this.enable('cache views');76+ });77+};78+79+/**80+ * Inherit from `connect.HTTPServer`.81+ */82+83+Server.prototype.__proto__ = connect.HTTPServer.prototype;84+85+/**86+ * Support swappable querystring parsers.87+ */88+89+exports.parseQueryString = queryString.parse;90+91+/**92+ * Proxy in order to register error handlers.93+ */94+95+Server.prototype.listen = function(){96+ this.registerErrorHandlers();97+ connect.HTTPServer.prototype.listen.apply(this, arguments);98+};99+100+/**101+ * Proxy in order to register error handlers.102+ */103+104+Server.prototype.listenFD = function(){105+ this.registerErrorHandlers();106+ connect.HTTPServer.prototype.listenFD.apply(this, arguments);107+};108+109+/**110+ * When using the vhost() middleware register error handlers.111+ */112+113+Server.prototype.onvhost = function(){114+ this.registerErrorHandlers();115+};116+117+/**118+ * Register error handlers. This is automatically119+ * called from within `Server#listen()` and `Server#listenFD()`.120+ *121+ * @return {Server} for chaining122+ * @api public123+ */124+125+Server.prototype.registerErrorHandlers = function(){126+ this.errorHandlers.forEach(function(fn){127+ this.use(function(err, req, res, next){128+ fn.apply(this, arguments);129+ });130+ }, this);131+ return this;132+};133+134+/**135+ * Proxy `connect.HTTPServer#use()` to apply settings to136+ * mounted applications.137+ *138+ * @param {String|Function|Server} route139+ * @param {Function|Server} middleware140+ * @return {Server} for chaining141+ * @api public142+ */143+144+Server.prototype.use = function(route, middleware){145+ if (typeof route !== 'string') {146+ middleware = route, route = '/';147+ }148+149+ connect.HTTPServer.prototype.use.call(this, route, middleware);150+151+ // Mounted an app152+ if (middleware instanceof Server) {153+ // Home is /:route/:home154+ var app = middleware155+ , home = app.set('home');156+ if (home === '/') home = '';157+ app.set('home', (app.route || '') + home);158+ app.parent = this;159+ // Mounted hook160+ if (app.__mounted) app.__mounted.call(app, this);161+ }162+163+ return this;164+};165+166+/**167+ * Assign a callback `fn` which is called168+ * when this `Server` is passed to `Server#use()`.169+ *170+ * Examples:171+ *172+ * var app = express.createServer(),173+ * blog = express.createServer();174+ *175+ * blog.mounted(function(parent){176+ * // parent is app177+ * // "this" is blog178+ * });179+ *180+ * app.use(blog);181+ *182+ * @param {Function} fn183+ * @return {Server} for chaining184+ * @api public185+ */186+187+Server.prototype.mounted = function(fn){188+ this.__mounted = fn;189+ return this;190+};191+192+/**193+ * See: view.register.194+ *195+ * @return {Server} for chaining196+ * @api public197+ */198+199+Server.prototype.register = function(){200+ view.register.apply(this, arguments);201+ return this;202+};203+204+/**205+ * Register the given view helpers `obj`. This method206+ * can be called several times to apply additional helpers.207+ *208+ * @param {Object} obj209+ * @return {Server} for chaining210+ * @api public211+ */212+213+Server.prototype.helpers = 214+Server.prototype.locals = function(obj){215+ utils.merge(this.viewHelpers, obj);216+ return this;217+};218+219+/**220+ * Register the given dynamic view helpers `obj`. This method221+ * can be called several times to apply additional helpers.222+ *223+ * @param {Object} obj224+ * @return {Server} for chaining225+ * @api public226+ */227+228+Server.prototype.dynamicHelpers = function(obj){229+ utils.merge(this.dynamicViewHelpers, obj);230+ return this;231+};232+233+/**234+ * Map the given param placeholder `name`(s) to the given callback `fn`.235+ *236+ * Param mapping is used to provide pre-conditions to routes237+ * which us normalized placeholders. For example ":user_id" may238+ * attempt to load the user from the database, where as ":num" may 239+ * pass the value through `parseInt(num, 10)`.240+ *241+ * When the callback function accepts only a single argument, the242+ * value of placeholder is passed:243+ *244+ * app.param('page', function(n){ return parseInt(n, 10); });245+ *246+ * After which "/users/:page" would automatically provide us with247+ * an integer for `req.params.page`. If desired we could use the callback 248+ * signature shown below, and immediately `next(new Error('invalid page'))`249+ * when `parseInt` fails.250+ *251+ * Alternatively the callback may accept the request, response, next, and252+ * the value, acting like middlware:253+ *254+ * app.param('userId', function(req, res, next, id){255+ * User.find(id, function(err, user){256+ * if (err) {257+ * next(err);258+ * } else if (user) {259+ * req.user = user;260+ * next();261+ * } else {262+ * next(new Error('failed to load user'));263+ * }264+ * });265+ * });266+ *267+ * Now every time ":userId" is present, the associated user object268+ * will be loaded and assigned before the route handler is invoked.269+ *270+ * @param {String|Array} name271+ * @param {Function} fn272+ * @return {Server} for chaining273+ * @api public274+ */275+276+Server.prototype.param = function(name, fn){277+ if (Array.isArray(name)) {278+ name.forEach(function(name){279+ this.param(name, fn);280+ }, this);281+ } else {282+ if (':' == name[0]) name = name.substr(1);283+ this.routes.param(name, fn);284+ }285+ return this;286+};287+288+/**289+ * Assign a custom exception handler callback `fn`.290+ * These handlers are always _last_ in the middleware stack.291+ *292+ * @param {Function} fn293+ * @return {Server} for chaining294+ * @api public295+ */296+297+Server.prototype.error = function(fn){298+ this.errorHandlers.push(fn);299+ return this;300+};301+302+/**303+ * Register the given callback `fn` for the given `type`.304+ *305+ * @param {String} type306+ * @param {Function} fn307+ * @return {Server} for chaining308+ * @api public309+ */310+311+Server.prototype.is = function(type, fn){312+ if (!fn) return this.isCallbacks[type];313+ this.isCallbacks[type] = fn;314+ return this;315+};316+317+/**318+ * Assign `setting` to `val`, or return `setting`'s value.319+ * Mounted servers inherit their parent server's settings.320+ *321+ * @param {String} setting322+ * @param {String} val323+ * @return {Server|Mixed} for chaining, or the setting value324+ * @api public325+ */326+327+Server.prototype.set = function(setting, val){328+ if (val === undefined) {329+ if (this.settings.hasOwnProperty(setting)) {330+ return this.settings[setting];331+ } else if (this.parent) {332+ return this.parent.set(setting);333+ }334+ } else {335+ this.settings[setting] = val;336+ return this;337+ }338+};339+340+/**341+ * Check if `setting` is enabled.342+ *343+ * @param {String} setting344+ * @return {Boolean}345+ * @api public346+ */347+348+Server.prototype.enabled = function(setting){349+ return !!this.set(setting);350+};351+352+/**353+ * Check if `setting` is disabled.354+ *355+ * @param {String} setting356+ * @return {Boolean}357+ * @api public358+ */359+360+Server.prototype.disabled = function(setting){361+ return !this.set(setting);362+};363+364+/**365+ * Enable `setting`.366+ *367+ * @param {String} setting368+ * @return {Server} for chaining369+ * @api public370+ */371+372+Server.prototype.enable = function(setting){373+ return this.set(setting, true);374+};375+376+/**377+ * Disable `setting`.378+ *379+ * @param {String} setting380+ * @return {Server} for chaining381+ * @api public382+ */383+384+Server.prototype.disable = function(setting){385+ return this.set(setting, false);386+};387+388+/**389+ * Redirect `key` to `url`.390+ *391+ * @param {String} key392+ * @param {String} url393+ * @return {Server} for chaining394+ * @api public395+ */396+397+Server.prototype.redirect = function(key, url){398+ this.redirects[key] = url;399+ return this;400+};401+402+/**403+ * Configure callback for the given `env`.404+ *405+ * @param {String} env406+ * @param {Function} fn407+ * @return {Server} for chaining408+ * @api public409+ */410+411+Server.prototype.configure = function(env, fn){412+ if (typeof env === 'function') {413+ fn = env, env = 'all';414+ }415+ if ('all' == env || env == this.settings.env) {416+ fn.call(this);417+ }418+ return this;419+};420+421+// Generate routing methods422+423+function generateMethod(method){424+ Server.prototype[method] = function(path, fn){425+ var self = this;426+427+ // Ensure router is mounted428+ if (!this.__usedRouter) {429+ this.use(this.router);430+ }431+432+ // Route specific middleware support433+ if (arguments.length > 2) {434+ var args = Array.prototype.slice.call(arguments, 1);435+ fn = args.pop();436+ (function stack(middleware){437+ middleware.forEach(function(fn){438+ if (Array.isArray(fn)) {439+ stack(fn);440+ } else {441+ self[method](path, fn);442+ }443+ });444+ })(args);445+ }446+447+ // Generate the route448+ this.routes[method](path, fn);449+ return this;450+ };451+ return arguments.callee;452+}453+454+methods.forEach(generateMethod);455+456+// Alias delete as "del"457+458+Server.prototype.del = Server.prototype.delete;deleted:lib/server.js-458 removed
1-2-/*!3- * Express - Server4- * Copyright(c) 2010 TJ Holowaychuk <tj@vision-media.ca>5- * MIT Licensed6- */7-8-/**9- * Module dependencies.10- */11-12-var queryString = require('querystring')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;19-20-/**21- * Initialize a new `Server` with optional `middleware`.22- *23- * @param {Array} middleware24- * @api public25- */26-27-var Server = exports = module.exports = function Server(middleware){28- var self = this;29- this.settings = {};30- this.redirects = {};31- this.isCallbacks = {};32- this.viewHelpers = {};33- this.dynamicViewHelpers = {};34- this.errorHandlers = [];35- connect.HTTPServer.call(this, []);36-37- // Default "home" to / 38- this.set('home', '/');39-40- // Set "env" to NODE_ENV, defaulting to "development"41- this.set('env', process.env.NODE_ENV || 'development');42-43- // Expose objects to each other44- this.use(function(req, res, next){45- req.query = req.query || {};46- res.headers = { 'X-Powered-By': 'Express' };47- req.app = res.app = self;48- req.res = res;49- res.req = req;50- req.next = next;51- // Assign req.params.get52- if (req.url.indexOf('?') > 0) {53- var query = url.parse(req.url).query;54- req.query = exports.parseQueryString(query);55- }56- next();57- });58-59- // Apply middleware60- if (middleware) {61- middleware.forEach(function(fn){62- self.use(fn);63- });64- }65-66- // Use router, expose as app.get(), etc67- var fn = router(function(app){ self.routes = app; });68- this.__defineGetter__('router', function(){69- this.__usedRouter = true;70- return fn;71- });72-73- // Default production configuration74- this.configure('production', function(){75- this.enable('cache views');76- });77-};78-79-/**80- * Inherit from `connect.HTTPServer`.81- */82-83-Server.prototype.__proto__ = connect.HTTPServer.prototype;84-85-/**86- * Support swappable querystring parsers.87- */88-89-exports.parseQueryString = queryString.parse;90-91-/**92- * Proxy in order to register error handlers.93- */94-95-Server.prototype.listen = function(){96- this.registerErrorHandlers();97- connect.HTTPServer.prototype.listen.apply(this, arguments);98-};99-100-/**101- * Proxy in order to register error handlers.102- */103-104-Server.prototype.listenFD = function(){105- this.registerErrorHandlers();106- connect.HTTPServer.prototype.listenFD.apply(this, arguments);107-};108-109-/**110- * When using the vhost() middleware register error handlers.111- */112-113-Server.prototype.onvhost = function(){114- this.registerErrorHandlers();115-};116-117-/**118- * Register error handlers. This is automatically119- * called from within `Server#listen()` and `Server#listenFD()`.120- *121- * @return {Server} for chaining122- * @api public123- */124-125-Server.prototype.registerErrorHandlers = function(){126- this.errorHandlers.forEach(function(fn){127- this.use(function(err, req, res, next){128- fn.apply(this, arguments);129- });130- }, this);131- return this;132-};133-134-/**135- * Proxy `connect.HTTPServer#use()` to apply settings to136- * mounted applications.137- *138- * @param {String|Function|Server} route139- * @param {Function|Server} middleware140- * @return {Server} for chaining141- * @api public142- */143-144-Server.prototype.use = function(route, middleware){145- if (typeof route !== 'string') {146- middleware = route, route = '/';147- }148-149- connect.HTTPServer.prototype.use.call(this, route, middleware);150-151- // Mounted an app152- if (middleware instanceof Server) {153- // Home is /:route/:home154- var app = middleware155- , home = app.set('home');156- if (home === '/') home = '';157- app.set('home', (app.route || '') + home);158- app.parent = this;159- // Mounted hook160- if (app.__mounted) app.__mounted.call(app, this);161- }162-163- return this;164-};165-166-/**167- * Assign a callback `fn` which is called168- * when this `Server` is passed to `Server#use()`.169- *170- * Examples:171- *172- * var app = express.createServer(),173- * blog = express.createServer();174- *175- * blog.mounted(function(parent){176- * // parent is app177- * // "this" is blog178- * });179- *180- * app.use(blog);181- *182- * @param {Function} fn183- * @return {Server} for chaining184- * @api public185- */186-187-Server.prototype.mounted = function(fn){188- this.__mounted = fn;189- return this;190-};191-192-/**193- * See: view.register.194- *195- * @return {Server} for chaining196- * @api public197- */198-199-Server.prototype.register = function(){200- view.register.apply(this, arguments);201- return this;202-};203-204-/**205- * Register the given view helpers `obj`. This method206- * can be called several times to apply additional helpers.207- *208- * @param {Object} obj209- * @return {Server} for chaining210- * @api public211- */212-213-Server.prototype.helpers = 214-Server.prototype.locals = function(obj){215- utils.merge(this.viewHelpers, obj);216- return this;217-};218-219-/**220- * Register the given dynamic view helpers `obj`. This method221- * can be called several times to apply additional helpers.222- *223- * @param {Object} obj224- * @return {Server} for chaining225- * @api public226- */227-228-Server.prototype.dynamicHelpers = function(obj){229- utils.merge(this.dynamicViewHelpers, obj);230- return this;231-};232-233-/**234- * Map the given param placeholder `name`(s) to the given callback `fn`.235- *236- * Param mapping is used to provide pre-conditions to routes237- * which us normalized placeholders. For example ":user_id" may238- * attempt to load the user from the database, where as ":num" may 239- * pass the value through `parseInt(num, 10)`.240- *241- * When the callback function accepts only a single argument, the242- * value of placeholder is passed:243- *244- * app.param('page', function(n){ return parseInt(n, 10); });245- *246- * After which "/users/:page" would automatically provide us with247- * an integer for `req.params.page`. If desired we could use the callback 248- * signature shown below, and immediately `next(new Error('invalid page'))`249- * when `parseInt` fails.250- *251- * Alternatively the callback may accept the request, response, next, and252- * the value, acting like middlware:253- *254- * app.param('userId', function(req, res, next, id){255- * User.find(id, function(err, user){256- * if (err) {257- * next(err);258- * } else if (user) {259- * req.user = user;260- * next();261- * } else {262- * next(new Error('failed to load user'));263- * }264- * });265- * });266- *267- * Now every time ":userId" is present, the associated user object268- * will be loaded and assigned before the route handler is invoked.269- *270- * @param {String|Array} name271- * @param {Function} fn272- * @return {Server} for chaining273- * @api public274- */275-276-Server.prototype.param = function(name, fn){277- if (Array.isArray(name)) {278- name.forEach(function(name){279- this.param(name, fn);280- }, this);281- } else {282- if (':' == name[0]) name = name.substr(1);283- this.routes.param(name, fn);284- }285- return this;286-};287-288-/**289- * Assign a custom exception handler callback `fn`.290- * These handlers are always _last_ in the middleware stack.291- *292- * @param {Function} fn293- * @return {Server} for chaining294- * @api public295- */296-297-Server.prototype.error = function(fn){298- this.errorHandlers.push(fn);299- return this;300-};301-302-/**303- * Register the given callback `fn` for the given `type`.304- *305- * @param {String} type306- * @param {Function} fn307- * @return {Server} for chaining308- * @api public309- */310-311-Server.prototype.is = function(type, fn){312- if (!fn) return this.isCallbacks[type];313- this.isCallbacks[type] = fn;314- return this;315-};316-317-/**318- * Assign `setting` to `val`, or return `setting`'s value.319- * Mounted servers inherit their parent server's settings.320- *321- * @param {String} setting322- * @param {String} val323- * @return {Server|Mixed} for chaining, or the setting value324- * @api public325- */326-327-Server.prototype.set = function(setting, val){328- if (val === undefined) {329- if (this.settings.hasOwnProperty(setting)) {330- return this.settings[setting];331- } else if (this.parent) {332- return this.parent.set(setting);333- }334- } else {335- this.settings[setting] = val;336- return this;337- }338-};339-340-/**341- * Check if `setting` is enabled.342- *343- * @param {String} setting344- * @return {Boolean}345- * @api public346- */347-348-Server.prototype.enabled = function(setting){349- return !!this.set(setting);350-};351-352-/**353- * Check if `setting` is disabled.354- *355- * @param {String} setting356- * @return {Boolean}357- * @api public358- */359-360-Server.prototype.disabled = function(setting){361- return !this.set(setting);362-};363-364-/**365- * Enable `setting`.366- *367- * @param {String} setting368- * @return {Server} for chaining369- * @api public370- */371-372-Server.prototype.enable = function(setting){373- return this.set(setting, true);374-};375-376-/**377- * Disable `setting`.378- *379- * @param {String} setting380- * @return {Server} for chaining381- * @api public382- */383-384-Server.prototype.disable = function(setting){385- return this.set(setting, false);386-};387-388-/**389- * Redirect `key` to `url`.390- *391- * @param {String} key392- * @param {String} url393- * @return {Server} for chaining394- * @api public395- */396-397-Server.prototype.redirect = function(key, url){398- this.redirects[key] = url;399- return this;400-};401-402-/**403- * Configure callback for the given `env`.404- *405- * @param {String} env406- * @param {Function} fn407- * @return {Server} for chaining408- * @api public409- */410-411-Server.prototype.configure = function(env, fn){412- if (typeof env === 'function') {413- fn = env, env = 'all';414- }415- if ('all' == env || env == this.settings.env) {416- fn.call(this);417- }418- return this;419-};420-421-// Generate routing methods422-423-function generateMethod(method){424- Server.prototype[method] = function(path, fn){425- var self = this;426-427- // Ensure router is mounted428- if (!this.__usedRouter) {429- this.use(this.router);430- }431-432- // Route specific middleware support433- if (arguments.length > 2) {434- var args = Array.prototype.slice.call(arguments, 1);435- fn = args.pop();436- (function stack(middleware){437- middleware.forEach(function(fn){438- if (Array.isArray(fn)) {439- stack(fn);440- } else {441- self[method](path, fn);442- }443- });444- })(args);445- }446-447- // Generate the route448- this.routes[method](path, fn);449- return this;450- };451- return arguments.callee;452-}453-454-methods.forEach(generateMethod);455-456-// Alias delete as "del"457-458-Server.prototype.del = Server.prototype.delete;modified:test/express.test.js+1 added-1 removed
9 unmodified lines10 11 module.exports = {12 'test inheritance': function(){13 var server = express.createServer();14- server.should.be.an.instanceof(connect.Server);14+ server.should.be.an.instanceof(connect.HTTPServer);15 },16 17 'test connect middleware autoloaders': function(){18 express.errorHandler.should.equal(connect.errorHandler);507 unmodified linesmodified:test/view.test.js+1 added-1 removed
389 unmodified lines390 session: function(req, res){391 ++calls;392 req.should.be.a('object');393 res.should.be.a('object');394- this.should.be.an.instanceof(express.Server);394+ this.should.equal(app);395 return req.session;396 }397 });398 505 unmodified lines