Skip to content

Commit

Permalink
fix(plugins): save req._matchedVersion (#1642)
Browse files Browse the repository at this point in the history
  • Loading branch information
hekike committed Apr 10, 2018
1 parent dc7336b commit 69f917a
Show file tree
Hide file tree
Showing 3 changed files with 28 additions and 18 deletions.
33 changes: 19 additions & 14 deletions docs/index.md
Expand Up @@ -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);
```
Expand Down Expand Up @@ -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
Expand All @@ -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:
Expand Down
4 changes: 3 additions & 1 deletion lib/plugins/conditionalHandler.js
Expand Up @@ -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;
}
Expand Down
9 changes: 6 additions & 3 deletions test/plugins/conditionalHandler.test.js
Expand Up @@ -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();
};
}
Expand Down Expand Up @@ -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'
}
])
Expand Down

0 comments on commit 69f917a

Please sign in to comment.