Skip to content
Myr

using connect.proto.use

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 d7da406 · Browse files · 2 files+532 added−1 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

2 files+532 added−1 removed

  • other:+532 added−1 removed

2 files+532 added−1 removed

modified:lib/express.js+1 added
modified:lib/proto.js+531 added-1 removed
12module.exports = { foo: 'bar' };2/*!3 * Express - proto4 * Copyright(c) 2010 TJ Holowaychuk <tj@vision-media.ca>5 * MIT Licensed6 */78/**9 * Module dependencies.10 */1112var connect = require('connect')13 , router = require('./router')14 , Router = require('./router')15 , view = require('./view')16 , toArray = require('./utils').toArray17 , methods = router.methods.concat('del', 'all')18 , res = require('./response')19 , url = require('url')20 , utils = connect.utils21 , qs = require('qs');2223/**24 * Expose `HTTPServer`.25 */2627var app = exports = module.exports = {};2829/**30 * Initialize the server.31 *32 * @param {Array} middleware33 * @api private34 */3536app.init = function(middleware){37 var self = this;38 this.cache = {};39 this.settings = {};40 this.redirects = {};41 this.isCallbacks = {};4243 this.set('home', '/');44 this.set('env', process.env.NODE_ENV || 'development');45 this.use(connect.query());4647 /**48 * Assign several locals with the given `obj`,49 * or return the locals.50 *51 * @param {Object} obj52 * @return {Object|HTTPServer}53 * @api public54 */5556 this.locals = function(obj){57 for (var key in obj) {58 self.locals[key] = obj[key];59 }60 return self;61 };6263 // expose objects to each other64 this.use(function(req, res, next){65 var charset;66 req.query = req.query || {};67 res.setHeader('X-Powered-By', 'Express');68 req.app = res.app = self;69 req.res = res;70 res.req = req;71 req.next = next;7273 // charset74 if (charset = self.set('charset')) res.charset = charset;7576 /**77 * Assign several locals with the given `obj`,78 * or return the locals.79 *80 * @param {Object} obj81 * @return {Object|ServerResponse}82 * @api public83 */8485 res.locals = function(obj){86 for (var key in obj) {87 res.locals[key] = obj[key];88 }89 return res;90 };9192 next();93 });9495 // apply middleware96 if (middleware) middleware.forEach(self.use.bind(self));9798 // router99 this.routes = new Router(this);100 this.__defineGetter__('router', function(){101 this.__usedRouter = true;102 return self.routes.middleware;103 });104105 // default locals106 this.locals.settings = this.settings;107108 // default development configuration109 this.configure('development', function(){110 this.enable('hints');111 });112113 // default production configuration114 this.configure('production', function(){115 this.enable('view cache');116 });117118 // route manipulation methods119 methods.forEach(function(method){120 self.lookup[method] = function(path){121 return self.routes.lookup(method, path);122 };123124 self.match[method] = function(path){125 return self.routes.match(method, path);126 };127128 self.remove[method] = function(path){129 return self.routes.lookup(method, path).remove();130 };131 });132133 // del -> delete134 self.lookup.del = self.lookup.delete;135 self.match.del = self.match.delete;136 self.remove.del = self.remove.delete;137};138139/**140 * Remove routes matching the given `path`.141 *142 * @param {Route} path143 * @return {Boolean}144 * @api public145 */146147app.remove = function(path){148 return this.routes.lookup('all', path).remove();149};150151/**152 * Lookup routes defined with a path153 * equivalent to `path`.154 *155 * @param {Stirng} path156 * @return {Array}157 * @api public158 */159160app.lookup = function(path){161 return this.routes.lookup('all', path);162};163164/**165 * Lookup routes matching the given `url`.166 *167 * @param {Stirng} url168 * @return {Array}169 * @api public170 */171172app.match = function(url){173 return this.routes.match('all', url);174};175176/**177 * Proxy `connect.HTTPServer#use()` to apply settings to178 * mounted applications.179 *180 * @param {String|Function|Server} route181 * @param {Function|Server} middleware182 * @return {Server} for chaining183 * @api public184 */185186app.use = function(route, middleware){187 var app, home, handle;188189 if ('string' != typeof route) {190 middleware = route, route = '/';191 }192193 // express app194 if (middleware.handle && middleware.set) app = middleware;195196 // restore .app property on req and res197 if (app) {198 app.route = route;199 middleware = function(req, res, next) {200 var orig = req.app;201 app.handle(req, res, function(err){202 req.app = res.app = orig;203 next(err);204 });205 };206 }207208 connect.proto.use.call(this, route, middleware);209210 // mounted an app, invoke the hook211 // and adjust some settings212 if (app) {213 base = this.set('basepath') || this.route;214 if ('/' == base) base = '';215 base = base + (app.set('basepath') || app.route);216 app.set('basepath', base);217 app.parent = this;218 if (app.__mounted) app.__mounted.call(app, this);219 }220221 return this;222};223224/**225 * Assign a callback `fn` which is called226 * when this `Server` is passed to `Server#use()`.227 *228 * Examples:229 *230 * var app = express.createServer()231 * , blog = express.createServer();232 *233 * blog.mounted(function(parent){234 * // parent is app235 * // "this" is blog236 * });237 *238 * app.use(blog);239 *240 * @param {Function} fn241 * @return {Server} for chaining242 * @api public243 */244245app.mounted = function(fn){246 this.__mounted = fn;247 return this;248};249250/**251 * See: view.register.252 *253 * @return {Server} for chaining254 * @api public255 */256257app.register = function(){258 view.register.apply(this, arguments);259 return this;260};261262/**263 * Map the given param placeholder `name`(s) to the given callback `fn`.264 * Register the given view helpers `obj`. This method265 * can be called several times to apply additional helpers.266 *267 * @param {Object} obj268 * @return {Server} for chaining269 * @api public270 */271272app.locals = function(obj){273 utils.merge(this._locals, obj);274 return this;275};276277/**278 * Map the given param placeholder `name`(s) to the given callback(s).279 *280 * Param mapping is used to provide pre-conditions to routes281 * which us normalized placeholders. This callback has the same282 * signature as regular middleware, for example below when ":userId"283 * is used this function will be invoked in an attempt to load the user.284 *285 * app.param('userId', function(req, res, next, id){286 * User.find(id, function(err, user){287 * if (err) {288 * next(err);289 * } else if (user) {290 * req.user = user;291 * next();292 * } else {293 * next(new Error('failed to load user'));294 * }295 * });296 * });297 *298 * Passing a single function allows you to map logic299 * to the values passed to `app.param()`, for example300 * this is useful to provide coercion support in a concise manner.301 *302 * The following example maps regular expressions to param values303 * ensuring that they match, otherwise passing control to the next304 * route:305 *306 * app.param(function(name, regexp){307 * if (regexp instanceof RegExp) {308 * return function(req, res, next, val){309 * var captures;310 * if (captures = regexp.exec(String(val))) {311 * req.params[name] = captures;312 * next();313 * } else {314 * next('route');315 * }316 * }317 * }318 * });319 *320 * We can now use it as shown below, where "/commit/:commit" expects321 * that the value for ":commit" is at 5 or more digits. The capture322 * groups are then available as `req.params.commit` as we defined323 * in the function above.324 *325 * app.param('commit', /^\d{5,}$/);326 *327 * For more of this useful functionality take a look328 * at [express-params](http://github.com/visionmedia/express-params).329 *330 * @param {String|Array|Function} name331 * @param {Function} fn332 * @return {Server} for chaining333 * @api public334 */335336app.param = function(name, fn){337 var self = this338 , fns = [].slice.call(arguments, 1);339340 // array341 if (Array.isArray(name)) {342 name.forEach(function(name){343 fns.forEach(function(fn){344 self.param(name, fn);345 });346 });347 // param logic348 } else if ('function' == typeof name) {349 this.routes.param(name);350 // single351 } else {352 if (':' == name[0]) name = name.substr(1);353 fns.forEach(function(fn){354 self.routes.param(name, fn);355 });356 }357358 return this;359};360361/**362 * Register the given callback `fn` for the given `type`.363 *364 * @param {String} type365 * @param {Function} fn366 * @return {Server} for chaining367 * @api public368 */369370app.is = function(type, fn){371 if (!fn) return this.isCallbacks[type];372 this.isCallbacks[type] = fn;373 return this;374};375376/**377 * Assign `setting` to `val`, or return `setting`'s value.378 * Mounted servers inherit their parent server's settings.379 *380 * @param {String} setting381 * @param {String} val382 * @return {Server|Mixed} for chaining, or the setting value383 * @api public384 */385386app.set = function(setting, val){387 if (val === undefined) {388 if (this.settings.hasOwnProperty(setting)) {389 return this.settings[setting];390 } else if (this.parent) {391 return this.parent.set(setting);392 }393 } else {394 this.settings[setting] = val;395 return this;396 }397};398399/**400 * Check if `setting` is enabled.401 *402 * @param {String} setting403 * @return {Boolean}404 * @api public405 */406407app.enabled = function(setting){408 return !!this.set(setting);409};410411/**412 * Check if `setting` is disabled.413 *414 * @param {String} setting415 * @return {Boolean}416 * @api public417 */418419app.disabled = function(setting){420 return !this.set(setting);421};422423/**424 * Enable `setting`.425 *426 * @param {String} setting427 * @return {Server} for chaining428 * @api public429 */430431app.enable = function(setting){432 return this.set(setting, true);433};434435/**436 * Disable `setting`.437 *438 * @param {String} setting439 * @return {Server} for chaining440 * @api public441 */442443app.disable = function(setting){444 return this.set(setting, false);445};446447/**448 * Redirect `key` to `url`.449 *450 * @param {String} key451 * @param {String} url452 * @return {Server} for chaining453 * @api public454 */455456app.redirect = function(key, url){457 this.redirects[key] = url;458 return this;459};460461/**462 * Configure callback for zero or more envs,463 * when no env is specified that callback will464 * be invoked for all environments. Any combination465 * can be used multiple times, in any order desired.466 *467 * Examples:468 *469 * app.configure(function(){470 * // executed for all envs471 * });472 *473 * app.configure('stage', function(){474 * // executed staging env475 * });476 *477 * app.configure('stage', 'production', function(){478 * // executed for stage and production479 * });480 *481 * @param {String} env...482 * @param {Function} fn483 * @return {Server} for chaining484 * @api public485 */486487app.configure = function(env, fn){488 var envs = 'all'489 , args = toArray(arguments);490 fn = args.pop();491 if (args.length) envs = args;492 if ('all' == envs || ~envs.indexOf(this.settings.env)) fn.call(this);493 return this;494};495496/**497 * Delegate `.VERB(...)` calls to `.route(VERB, ...)`.498 */499500methods.forEach(function(method){501 app[method] = function(path){502 if (1 == arguments.length) return this.routes.lookup(method, path);503 var args = [method].concat(toArray(arguments));504 if (!this.__usedRouter) this.use(this.router);505 return this.routes._route.apply(this.routes, args);506 }507});508509/**510 * Special-cased "all" method, applying the given route `path`,511 * middleware, and callback to _every_ HTTP method.512 *513 * @param {String} path514 * @param {Function} ...515 * @return {Server} for chaining516 * @api public517 */518519app.all = function(path){520 var args = arguments;521 if (1 == args.length) return this.routes.lookup('all', path);522 methods.forEach(function(method){523 if ('all' == method) return;524 app[method].apply(this, args);525 }, this);526 return this;527};528529// del -> delete alias530531app.del = app.delete;532