Added support for multiple callbacks for `app.param()`. Closes #801
Before adoption: this commit came in with the history the project adopted, so no landing records it.
you can also make several calls to `app.param()` for the same param name, which is equivalent to passing multiple in a single call
authored by Tj Holowaychuk · committed by Tj Holowaychuk · parent a2a7644 · Browse files · 3 files·+304 added−13 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
3 files+304 added−13 removed
- tests:+207 added−0 removed
- other:+97 added−13 removed
Provenance
- Commit
ca75492- Tree
08cce92- Author
Tj Holowaychuk <tj@vision-media.ca>- Committer
Tj Holowaychuk <tj@vision-media.ca>- Parent
a2a7644
3 files changed+304 added−13 removed
modified:lib/router/index.js+23 added-10 removed
77 unmodified lines78 if ('function' != typeof fn) {79 throw new Error('invalid param() call for ' + name + ', got ' + fn);80 }81 82- this.params[name] = fn;82+ (this.params[name] = this.params[name] || []).push(fn);83 return this;84 };85 86 /**95 unmodified lines182 , self = this;183 184 // route dispatch185 (function pass(i){186- var route186+ var paramCallbacks187+ , paramIndex = 0188+ , paramVal189+ , route190 , keys191+ , key192 , ret;193 194 // match next route195 function nextRoute() {14 unmodified lines210 req.params = route.params;211 keys = route.keys;212 i = 0;213 210- (function param(err) {211- var key = keys[i++]212- , val = key && req.params[key.name]213- , fn = key && params[key.name]214- , ret;214+ // param callbacks215+ function param(err) {216+ key = keys[i++];217+ paramVal = key && req.params[key.name];218+ paramCallbacks = key && params[key.name];219 220 try {221 if ('route' == err) {222 nextRoute();223 } else if (err) {224 next(err);221- } else if (fn && undefined !== val) {222- fn(req, res, param, val);225+ } else if (paramCallbacks && undefined !== paramVal) {226+ paramCallback();227 } else if (key) {228 param();229 } else {230 i = 0;1 unmodified line232 }233 } catch (err) {234 next(err);235 }232- })();236+ };237 238+ param();239+240+ // single param callbacks241+ function paramCallback(err) {242+ var fn = paramCallbacks[paramIndex++];243+ if (err || !fn) return param(err);244+ fn(req, res, paramCallback, paramVal, key.name);245+ }246+247 // invoke route middleware248 function middleware(err) {249 var fn = route.middleware[i++];250 if ('route' == err) {147 unmodified linesmodified:lib/http.js+74 added-3 removed
281 unmodified lines282 return this;283 };284 285 /**286+<<<<<<< HEAD287 * Map the given param placeholder `name`(s) to the given callback `fn`.288+=======289+ * Register the given view helpers `obj`. This method290+ * can be called several times to apply additional helpers.291 *292+ * @param {Object} obj293+ * @return {Server} for chaining294+ * @api public295+ */296+297+app.helpers =298+app.locals = function(obj){299+ utils.merge(this._locals, obj);300+ return this;301+};302+303+/**304+ * Register the given dynamic view helpers `obj`. This method305+ * can be called several times to apply additional helpers.306+ *307+ * @param {Object} obj308+ * @return {Server} for chaining309+ * @api public310+ */311+312+app.dynamicHelpers = function(obj){313+ utils.merge(this.dynamicViewHelpers, obj);314+ return this;315+};316+317+/**318+ * Map the given param placeholder `name`(s) to the given callback(s).319+ *320 * Param mapping is used to provide pre-conditions to routes321 * which us normalized placeholders. This callback has the same322 * signature as regular middleware, for example below when ":userId"323 * is used this function will be invoked in an attempt to load the user.10 unmodified lines334 * }335 * });336 * });337 *338+ * Passing a single function allows you to map logic339+ * to the values passed to `app.param()`, for example340+ * this is useful to provide coercion support in a concise manner.341+ *342+ * The following example maps regular expressions to param values343+ * ensuring that they match, otherwise passing control to the next344+ * route:345+ *346+ * app.param(function(name, regexp){347+ * if (regexp instanceof RegExp) {348+ * return function(req, res, next, val){349+ * var captures;350+ * if (captures = regexp.exec(String(val))) {351+ * req.params[name] = captures;352+ * next();353+ * } else {354+ * next('route');355+ * }356+ * }357+ * }358+ * });359+ *360+ * We can now use it as shown below, where "/commit/:commit" expects361+ * that the value for ":commit" is at 5 or more digits. The capture362+ * groups are then available as `req.params.commit` as we defined363+ * in the function above.364+ *365+ * app.param('commit', /^\d{5,}$/);366+ *367+ * For more of this useful functionality take a look368+ * at [express-params](http://github.com/visionmedia/express-params).369+ *370 * @param {String|Array|Function} name371 * @param {Function} fn372 * @return {Server} for chaining373 * @api public374 */375 376 app.param = function(name, fn){377+ var self = this378+ , fns = [].slice.call(arguments, 1);379+380 // array381 if (Array.isArray(name)) {382 name.forEach(function(name){383+ fns.forEach(function(fn){316- this.param(name, fn);317- }, this);384+ self.param(name, fn);385+ });386+ });387 // param logic388 } else if ('function' == typeof name) {389 this.routes.param(name);390 // single391 } else {392 if (':' == name[0]) name = name.substr(1);393+ fns.forEach(function(fn){324- this.routes.param(name, fn);394+ self.routes.param(name, fn);395+ });396 }397 398 return this;399 };173 unmodified linesmodified:test/router.test.js+207 added
72 unmodified lines73 calls.should.equal(3);74 });75 },76 77+ 'test app.param() multiple mapping functions': function(){78+ var app = express.createServer();79+80+ app.param(function(name, fn){81+ if (fn.length < 3) {82+ return function(req, res, next, val){83+ val = req.params[name] = fn(val);84+ if (false === val) {85+ next('route');86+ } else {87+ next();88+ }89+ };90+ }91+ });92+93+ app.param(function(name, range){94+ if (!~String(range).indexOf('..')) return;95+ var parts = range.split('..')96+ , from = parseInt(parts.shift())97+ , to = parseInt(parts.shift());98+99+ return function(req, res, next, val){100+ if (val < from || val > to) return next('route');101+ next();102+ }103+ });104+105+ app.param('user', Number);106+ app.param('user', '0..5');107+108+ app.get('/user/:user', function(req, res){109+ res.json(req.params.user);110+ });111+112+ assert.response(app,113+ { url: '/user/3' },114+ { body: '3' });115+116+ assert.response(app,117+ { url: '/user/6' },118+ { status: 404 });119+ },120+121+ 'test app.param() name passing': function(){122+ var app = express.createServer();123+ 124+ app.param(function(name, fn){125+ if (fn.length < 3) {126+ return function(req, res, next, val){127+ val = req.params[name] = fn(val);128+ if (false === val) {129+ next('route');130+ } else {131+ next();132+ }133+ };134+ }135+ });136+137+ function within(a, b) {138+ return function(req, res, next, val, name){139+ if (val < a || val > b) {140+ return next(new Error(name + ' should be within ' + a + '..' + b));141+ }142+ next();143+ }144+ }145+146+ app.param('user', Number);147+ app.param('user', within(0, 5));148+149+ app.get('/user/:user', function(req, res){150+ res.json(req.params.user);151+ });152+153+ app.use(function(err, req, res, next){154+ res.json({ error: err.message });155+ });156+157+ assert.response(app,158+ { url: '/user/0' },159+ { body: '0' });160+161+ assert.response(app,162+ { url: '/user/6' },163+ { body: '{"error":"user should be within 0..5"}' });164+ },165+166+ 'test app.param() multiple callbacks and array of params': function(){167+ var app = express.createServer();168+ var users = [{ name: 'tj' }];169+ var pets = [['tobi', 'loki', 'jane', 'manny', 'luna']];170+171+ function loadUser(req, res, next, id) {172+ req.user = users[id];173+ next();174+ }175+176+ function loadUserPets(req, res, next, id) {177+ req.user.pets = pets[id];178+ next();179+ }180+181+ app.param(['user_id', 'user'], loadUser, loadUserPets);182+183+ app.get('/user/:user_id', function(req, res){184+ res.send(req.user);185+ });186+187+ app.get('/account/:user', function(req, res){188+ res.send(req.user);189+ });190+191+ assert.response(app,192+ { url: '/account/0' },193+ { body: '{"name":"tj","pets":["tobi","loki","jane","manny","luna"]}' });194+195+ assert.response(app,196+ { url: '/user/0' },197+ { body: '{"name":"tj","pets":["tobi","loki","jane","manny","luna"]}' });198+ },199+200+ 'test app.param() multiple callbacks': function(){201+ var app = express.createServer();202+ var users = [{ name: 'tj' }];203+ var pets = [['tobi', 'loki', 'jane', 'manny', 'luna']];204+205+ function loadUser(req, res, next, id) {206+ req.user = users[id];207+ next();208+ }209+210+ function loadUserPets(req, res, next, id) {211+ req.user.pets = pets[id];212+ next();213+ }214+215+ app.param('user_id', loadUser, loadUserPets);216+217+ app.get('/user/:user_id', function(req, res){218+ res.send(req.user);219+ });220+221+ assert.response(app,222+ { url: '/user/0' },223+ { body: '{"name":"tj","pets":["tobi","loki","jane","manny","luna"]}' });224+ },225+226+ 'test app.param() multiple calls with error': function(){227+ var app = express.createServer();228+229+ var commits = ['foo', 'bar', 'baz'];230+231+ app.param('commit', function(req, res, next, id){232+ req.commit = parseInt(id);233+ if (isNaN(req.commit)) return next('route');234+ next();235+ });236+237+ app.param('commit', function(req, res, next, id){238+ req.commit = commits[req.commit];239+ next(new Error('failed'));240+ });241+242+ app.get('/commit/:commit', function(req, res){243+ res.send(req.commit);244+ });245+246+ assert.response(app,247+ { url: '/commit/0' },248+ { status: 500 });249+ },250+251+ 'test app.param() multiple calls': function(){252+ var app = express.createServer();253+254+ var commits = ['foo', 'bar', 'baz'];255+256+ app.param('commit', function(req, res, next, id){257+ req.commit = parseInt(id);258+ if (isNaN(req.commit)) return next('route');259+ next();260+ });261+262+ app.param('commit', function(req, res, next, id){263+ req.commit = commits[req.commit];264+ next();265+ });266+267+ app.get('/commit/:commit', function(req, res){268+ res.send(req.commit);269+ });270+271+ assert.response(app,272+ { url: '/commit/0' },273+ { body: 'foo' });274+275+ assert.response(app,276+ { url: '/commit/0x01' },277+ { body: 'bar' });278+279+ assert.response(app,280+ { url: '/commit/asdf' },281+ { status: 404 });282+ },283+284 'test app.param(fn)': function(){285 var app = express.createServer();286 287 app.param(function(name, fn){415 unmodified lines