koa-semver
Match middleware with Semantic Versioning.
Built with npm/node-semver to match familiar npm
style dependency syntax and usage, but for middleware and routes.
Requisites:
Installation
npm install --save koa-semver # with yarn: yarn add koa-semver
Usage
koa-semver
allows multiple usage options, but it is strongly recommended to use with koa-router
.
Basic Versioning
A sample Koa server would be:
"use strict"; const Koa = ;const Router = ;const Semver = ; const app = ;const router = ; // Add handlers by priority// (Descending order)const ver = Semverhandlers Semverhandlers Semverhandlers; // Newer middleware or routes should be placed on top// (Descending order)router; router; app; app;
Client side usage:
# Latest version $ curl http://localhost:3000/_/users$ curl -H "X-Semver: 2.10.1" http://localhost:3000/_/users # Latest version (headers has more priority than route param) $ curl -H "X-Semver: 2.10.1" http://localhost:3000/1.2.5/users
# Specific version $ curl http://localhost:3000/1.3.0/users$ curl http://localhost:3000/_/users?version=1.4.0
# Unknown version $ curl http://localhost:3000/3.0.0/users$ curl http://localhost:3000/0.1.0/usersNot Found
Semver state variable
It is possible to know about the requested and matching versions:
router;
Create a matcher
Sometimes we want to reuse the matching version, so we can:
const ver = ;ver; const matcher = ver; const router = ;router;router;
Another way is:
const app = ; const ver = ;ver; const router = ;router;router; app;
Multiple matching
It is responsibility of the developer to stop the middleware propagation. So it is possible to match multiples routes or add conditional middleware using koa-semver
;
const app = ;const router = ;const ver = ;ver; app; router; router; router; // ... app;
In this case a GET
request to /endpoint
with X-Semver: 1.2.0
will match the first two routes and will return:
["Hello!", "World!"]
Testing
Run Jest test suite with:
yarn test # With coverage yarn test -- --coverage # Watch for changes yarn test -- --watch