From 711a4897800e2ef8bc4a1a9c6cc833af71cd925d Mon Sep 17 00:00:00 2001 From: Jacob Quatier Date: Thu, 16 Jun 2016 16:18:11 -0700 Subject: [PATCH] Feature: Ability to find a route by a path * Adding method on router to find a route by a path * adding JSDocs for findByPath --- lib/router.js | 33 +++++++++++++++++++++++++++++++++ test/router.test.js | 22 ++++++++++++++++++++++ 2 files changed, 55 insertions(+) diff --git a/lib/router.js b/lib/router.js index 73fab6122..644b02669 100644 --- a/lib/router.js +++ b/lib/router.js @@ -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. diff --git a/test/router.test.js b/test/router.test.js index f1adb9c04..b8c4b425a 100644 --- a/test/router.test.js +++ b/test/router.test.js @@ -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(); +});