Created
September 21, 2018 19:42
-
-
Save Dugo03/63a141f55cba118a94da6c779d3234e9 to your computer and use it in GitHub Desktop.
Express API version - /v1, /v2, etc..
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const latest = 5; | |
module.exports = (req, res, next) => { | |
if (!req.params.version.match(/^v\d+$/)) { // /v1 or /v2 | |
return res.sendStatus(404); | |
} | |
req.version = parseInt(req.params.version.substr(1)); // 1 or 2 | |
if (!req.version || req.version > latest) { | |
return res.sendStatus(404); | |
} | |
next(); | |
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module.exports = (routeMap) => (req, res, next) => { | |
const key = Object.keys(routeMap) | |
.filter(version => version <= req.version) | |
.pop(); | |
const route = routeMap[key]; | |
return route(req, res, next); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Usage example: