Permalink
Browse files

add named params

  • Loading branch information...
1 parent d8d1ebf commit 4883cd376e9c614025e327b9f31ec84614fd6093 @caolan committed Oct 28, 2010
Showing with 37 additions and 3 deletions.
  1. +5 −1 README.md
  2. +3 −1 lib/dispatch.js
  3. +29 −1 test/test-dispatch.js
View
6 README.md
@@ -12,7 +12,7 @@ regular expressions for matching URLs and calling an associated function.
'/about': function(req, res, next){
...
},
- '/user': function(req, res, next){
+ '/user/:id': function(req, res, next, id){
...
},
'/user/posts': function(req, res, next){
@@ -28,6 +28,10 @@ Dispatch can be used with a straight-forward object literal containing view
functions keyed by URL. As you can see from the last URL in the list, captured
groups are passed to the matching function as an argument.
+You can also use :named parameters in a URL, which is just a more readable way
+of capturing ([^\/]+). Named parameters are passed to the matched function in
+the same way as normal regular expression groups.
+
So far so predictable. However, it is also possible to nest these objects as
you see fit:
View
4 lib/dispatch.js
@@ -32,7 +32,9 @@ function flattenKeys(obj, /*optional args: */acc, prefix, prev_method){
*/
function compileKeys(urls){
return urls.map(function(url){
- url[0] = new RegExp('^' + url[0] + '$');
+ // replace named params with regexp groups
+ var pattern = url[0].replace(/\/:\w+/g, '(?:/([^\/]+))');
+ url[0] = new RegExp('^' + pattern + '$');
return url;
});
}
View
30 test/test-dispatch.js
@@ -1,4 +1,4 @@
-var dispatch = require('dispatch');
+var dispatch = require('../lib/dispatch');
exports['simple match'] = function(test){
test.expect(3);
@@ -208,3 +208,31 @@ exports['whitespace between method and pattern'] = function (test) {
handle_req(request, 'response', 'next');
test.done();
};
+
+exports['named param'] = function (test) {
+ var request = {url: '/abc/test123'};
+ dispatch({
+ '/:name/test\\d{3}': function(req, res, next, name){
+ test.equals(req, request);
+ test.equals(res, 'response');
+ test.equals(next, 'next');
+ test.equals(name, 'abc');
+ test.done();
+ }
+ })(request, 'response', 'next');
+};
+
+exports['nested named param'] = function (test) {
+ var request = {url: '/test/123'};
+ dispatch({
+ '/test': {
+ '/:param': function(req, res, next, name){
+ test.equals(req, request);
+ test.equals(res, 'response');
+ test.equals(next, 'next');
+ test.equals(name, '123');
+ test.done();
+ }
+ }
+ })(request, 'response', 'next');
+};

0 comments on commit 4883cd3

Please sign in to comment.