From 4883cd376e9c614025e327b9f31ec84614fd6093 Mon Sep 17 00:00:00 2001 From: Caolan McMahon Date: Thu, 28 Oct 2010 18:59:29 +0100 Subject: [PATCH] add named params --- README.md | 6 +++++- lib/dispatch.js | 4 +++- test/test-dispatch.js | 30 +++++++++++++++++++++++++++++- 3 files changed, 37 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 175fa0e..886bce4 100644 --- a/README.md +++ b/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: diff --git a/lib/dispatch.js b/lib/dispatch.js index 0f4bd80..cb35cb7 100644 --- a/lib/dispatch.js +++ b/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; }); } diff --git a/test/test-dispatch.js b/test/test-dispatch.js index e2599db..794a23e 100644 --- a/test/test-dispatch.js +++ b/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'); +};