A tiny route/api semantic versioning library for Koa and Express.
npm install route-v
Gets the version from the URL (originalUrl) and expects Routes/APIs to look like Koa or Express middleware.
- Supports all semver ranges E.g. <2.x, *, ~1.0.0.
- Supports Koa and Express by default.
- Easily change the version source E.g, from URL to headers or both.
- Can be used to version any function (May require some configurations).
Migration from version 2 to 3 notes:
- Removed the deprecated property register returned by the function constructor, use v instead.
- Removed the deprecated property version returned by the function versionChecker, use range instead.
- versionExtractor now takes exactly the same arguments as your versioned routes (functions)
const Koa = ;const Router = ;const v = ;// This regex will check if the url has a version number in it.const baseUrl = '/(v\\d+.\\d+.\\d+)';const router =prefix: `/greetings`;router;const app = ;app;
curl localhost:3000/v0.0.0/greetings // hello curl localhost:3000/v1.0.0/greetings // hola curl localhost:3000/v2.0.0/greetings // hi
Global version check
// ... some omitted setup codeconst versionChecker = ;const vChecker =;router;exportsapp = ;exportsapp;
curl localhost:3000/v6.0.0/greetings // Version 6.0.0 is not compliant with version <5.x
Change extractor and path
If you want to use the header instead of the url.
const valid = ;// Points to the object "headers" from the first argument of your function (ctx in koa, req in express)// and returns the value of the key x-api-versionconst versionExtractor = ;const v = ;
Add a custom versionNotFoundErrorHandler
By default, an error will be thrown if the version requested was not found.
// This is for Koa, for express, a similar middleware can be passedconst versionNotFoundErrorHandler = ctx;const v = ;
Since the insertion order matters but it is not guaranteed for integers, the library assumes you know what you are doing when using integers as ranges. https://bugs.chromium.org/p/v8/issues/detail?id=164
Credits: Kudus to Avaq, his expertise have been extremely helpful.