Skip to content

Commit

Permalink
Feature: Ability to find a route by a path
Browse files Browse the repository at this point in the history
* Adding method on router to find a route by a path
* adding JSDocs for findByPath
  • Loading branch information
jquatier authored and micahr committed Jun 16, 2016
1 parent 6622dc5 commit 711a489
Show file tree
Hide file tree
Showing 2 changed files with 55 additions and 0 deletions.
33 changes: 33 additions & 0 deletions lib/router.js
Expand Up @@ -577,6 +577,39 @@ Router.prototype.find = function find(req, res, callback) {
));
};

/**
* Find a route by path. Scans the route list for a route with the same RegEx.
* i.e. /foo/:param1/:param2 would match an existing route with different
* parameter names /foo/:id/:name since the compiled RegExs match.
* @public
* @function findByPath
* @param {String | RegExp} path a path to find a route for.
* @param {Object} options an options object
* @returns {Object} returns the route if a match is found
*/
Router.prototype.findByPath = function findByPath(path, options) {
assert.string(path, 'path');
assert.object(options, 'options');
assert.string(options.method, 'options.method');

var route;
var routes = this.routes[options.method] || [];
var routeRegex = compileURL({
url: path,
flags: options.flags,
urlParamPattern: options.urlParamPattern,
strict: this.strict
});

for (var i = 0; i < routes.length; i++) {
if (routeRegex.toString() === routes[i].path.toString()) {
route = routes[i];
break;
}
}
return (route);
};


/**
* toString() serialization.
Expand Down
22 changes: 22 additions & 0 deletions test/router.test.js
Expand Up @@ -220,3 +220,25 @@ test('Default non-strict routing ignores trailing slash(es)', function (t) {

t.end();
});

test('Find existing route with path', function (t) {
var server = restify.createServer();
function noop () {}

var routePath = '/route/:withParam';
server.get(routePath, noop);

var foundRoute = server.router.findByPath(
'/route/:withADifferentParamName',
{ method: 'GET' }
);
t.equal(foundRoute.spec.path, routePath);

var notFoundRoute = server.router.findByPath(
'/route/:withADifferentParamName([A-Z]{2,3})',
{ method: 'GET' }
);
t.notOk(notFoundRoute);

t.end();
});

0 comments on commit 711a489

Please sign in to comment.