Permalink
Browse files

Added support for app.param(fn) to define param logic

  • Loading branch information...
1 parent d6ef90d commit b1a7310263fe1bc086c4ec085eeb28fe46f3b25c @tj tj committed May 23, 2011
Showing with 47 additions and 14 deletions.
  1. +7 −1 lib/http.js
  2. +40 −13 lib/router/index.js
View
@@ -348,21 +348,27 @@ app.dynamicHelpers = function(obj){
* Now every time ":userId" is present, the associated user object
* will be loaded and assigned before the route handler is invoked.
*
- * @param {String|Array} name
+ * @param {String|Array|Function} name
* @param {Function} fn
* @return {Server} for chaining
* @api public
*/
app.param = function(name, fn){
+ // array
if (Array.isArray(name)) {
name.forEach(function(name){
this.param(name, fn);
}, this);
+ // param logic
+ } else if ('function' == typeof name) {
+ this.routes.param(name);
+ // single
} else {
if (':' == name[0]) name = name.substr(1);
this.routes.param(name, fn);
}
+
return this;
};
View
@@ -39,33 +39,60 @@ function Router(app) {
this.app = app;
this.routes = {};
this.params = {};
+ this._params = [];
+
this.middleware = function(req, res, next){
self._dispatch(req, res, next);
};
+
+ // treat functions with arity < 3
+ // to simply return a value
+ this.param(function(name, fn){
+ if (fn.length < 3) {
+ return function(req, res, next){
+ var val = req.params[name];
+ val = req.params[name] = fn(val);
+ if (invalidParamReturnValue(val)) {
+ next('route');
+ } else {
+ next();
+ }
+ };
+ }
+ })
}
/**
* Register a param callback `fn` for the given `name`.
*
- * @param {String} name
+ * @param {String|Function} name
* @param {Function} fn
* @return {Router} for chaining
* @api public
*/
Router.prototype.param = function(name, fn){
- var callback = fn;
-
- if (fn.length < 3) {
- fn = function(req, res, next){
- var val = req.params[name];
- val = req.params[name] = callback(val);
- if (invalidParamReturnValue(val)) {
- next('route');
- } else {
- next();
- }
- };
+ // param logic
+ if ('function' == typeof name) {
+ this._params.push(name);
+ return;
+ }
+
+ // apply param functions
+ var params = this._params
+ , len = params.length
+ , ret;
+
+ for (var i = 0; i < len; ++i) {
+ if (ret = params[i](name, fn)) {
+ fn = ret;
+ }
+ }
+
+ // ensure we end up with a
+ // middleware function
+ if ('function' != typeof fn) {
+ throw new Error('invalid param() call for ' + name + ', got ' + fn);
}
this.params[name] = fn;

0 comments on commit b1a7310

Please sign in to comment.