diff --git a/docs/index.md b/docs/index.md index 13def4f14..ddc402000 100644 --- a/docs/index.md +++ b/docs/index.md @@ -321,9 +321,10 @@ function sendV2(req, res, next) { return next(); } -var PATH = '/hello/:name'; -server.get({path: PATH, version: '1.1.3'}, sendV1); -server.get({path: PATH, version: '2.0.0'}, sendV2); +server.get('/hello/:name', restify.plugins.conditionalHandler([ + { version: '1.1.3', handler: sendV1 }, + { version: '2.0.0', handler: sendV2 } +])); server.listen(8080); ``` @@ -357,7 +358,9 @@ creation time. Lastly, you can support multiple versions in the API by using an array: ```js -server.get({path: PATH, version: ['2.0.0', '2.1.0', '2.2.0']}, sendV2); +server.get('/hello/:name' restify.plugins.conditionalHandler([ + { version: ['2.0.0', '2.1.0', '2.2.0'], handler: sendV2 } +])); ``` In this case you may need to know more information such as what the original @@ -366,16 +369,18 @@ supported version array was. Two methods make this info available: ```js var PATH = '/version/test'; -server.get({ - path: PATH, - version: ['2.0.0', '2.1.0', '2.2.0'] -}, function (req, res, next) { - res.send(200, { - requestedVersion: req.version(), - matchedVersion: req.matchedVersion() - }); - return next(); -}); +server.get('/version/test', restify.plugins.conditionalHandler([ + { + version: ['2.0.0', '2.1.0', '2.2.0'], + handler: function (req, res, next) { + res.send(200, { + requestedVersion: req.version(), + matchedVersion: req.matchedVersion() + }); + return next(); + } + } +])); ``` Hitting this route will respond as below: diff --git a/lib/plugins/conditionalHandler.js b/lib/plugins/conditionalHandler.js index 555d62b1d..7ddf55c1b 100644 --- a/lib/plugins/conditionalHandler.js +++ b/lib/plugins/conditionalHandler.js @@ -174,7 +174,9 @@ function conditionalHandler(candidates) { // Add api-version response header res.header('api-version', maxVersion); - + // Store matched version on request internal + req._matchedVersion = maxVersion; + // Run handler reqCandidates[maxVersionIndex].handler(req, res, next); return; } diff --git a/test/plugins/conditionalHandler.test.js b/test/plugins/conditionalHandler.test.js index cb4dc0a0f..dee2b6b08 100644 --- a/test/plugins/conditionalHandler.test.js +++ b/test/plugins/conditionalHandler.test.js @@ -14,9 +14,12 @@ var SERVER; var CLIENT; var PORT; -function handlerFactory(response) { +function handlerFactory(response, version) { return function handler(req, res, next) { res.send(response); + if (version) { + assert.equal(req.matchedVersion(), version); + } next(); }; } @@ -51,11 +54,11 @@ describe('conditional request', function() { '/', restify.plugins.conditionalHandler([ { - handler: handlerFactory('v1.1.0'), + handler: handlerFactory('v1.1.0', 'v1.1.0'), version: 'v1.1.0' }, { - handler: handlerFactory('v1.2.0'), + handler: handlerFactory('v1.2.0', 'v1.2.0'), version: 'v1.2.0' } ])