Permalink
Browse files

Added regexp support

  • Loading branch information...
1 parent cc5015c commit f7ac483f46a3dfcdd319b72fffd485a760320954 @tj tj committed May 23, 2011
Showing with 50 additions and 0 deletions.
  1. +19 −0 lib/express-params.js
  2. +31 −0 test/test.params.js
View
@@ -20,6 +20,25 @@ exports.version = '0.0.1';
exports.extend = function(app){
exports.extend.returnValue(app);
+ exports.extend.regexp(app);
+};
+
+exports.extend.regexp = function(app){
+ app.param(function(name, fn){
+ if (fn instanceof RegExp) {
+ return function(req, res, next){
+ var val = req.params[name]
+ , captures;
+
+ if (captures = fn.exec(String(val))) {
+ req.params[name] = captures;
+ next();
+ } else {
+ next('route');
+ }
+ }
+ }
+ });
};
/**
View
@@ -49,5 +49,36 @@ module.exports = {
assert.response(app,
{ url: '/error/hey' },
{ status: 500 });
+ },
+
+ 'regexp': function(){
+ var app = express.createServer();
+ params.extend(app);
+
+ app.param('range', /^(\w+)\.\.(\w+)?$/);
+
+ app.get('/range/:range', function(req, res, next){
+ var range = req.params.range;
+ res.send('from ' + range[1] + ' to ' + range[2]);
+ });
+
+ app.param('username', /^[a-z_]+$/);
+
+ app.get('/user/:username', function(req, res, next){
+ var username = req.params.username;
+ res.send('user ' + username);
+ });
+
+ assert.response(app,
+ { url: '/user/tj' },
+ { body: 'user tj' });
+
+ assert.response(app,
+ { url: '/user/23' },
+ { status: 404 });
+
+ assert.response(app,
+ { url: '/range/1..5' },
+ { body: 'from 1 to 5' });
}
}

0 comments on commit f7ac483

Please sign in to comment.