koa-router-version
Semantic Versioning routing for Koa
Allows you to use Semantic Versioning routes.
Requisites:
- Node.js >= 7.6.0
- Koa >= 2.0.0
- Koa Router >= 7.0.0
Installation
npm install --save koa-router-version # with yarn: yarn add koa-router-version
Usage
A basic usage:
const Koa = ;const Router = ;const api = ; const list = ;const detail = ;const detail2 = ; const app = ;const router = ; // Defines a version 1.0.0 for todo listrouter; // Defines 2 versions (order is NOT important)router // You can specify a route param as version. Will accept both /todo/321 and /v1/todo/321 router app; app;
For client usage:
# Latest version $ curl -i http://localhost:3000/todo/1HTTP/1.1 200 AcceptedX-Api-Version: 2.1.3<more headers> {"todo": {}} # Specifying a version $ curl -i -H "Accept-Version: ^1.0" http://localhost:3000/todo/1HTTP/1.1 200 AcceptedX-Api-Version: 1.1.0<more headers> {"todo": {}} # Specifying a version via path $ curl -i http://localhost:3000/v1/todo/1HTTP/1.1 200 AcceptedX-Api-Version: 1.1.0<more headers> {"todo": {}} $ curl -i -H "Accept-Version: ~2" http://localhost:3000/todo/1HTTP/1.1 200 AcceptedX-Api-Version: 2.1.3<more headers> {"todo": {}} # Path has higher priority than header $ curl -i -H "Accept-Version: ~2" http://localhost:3000/v1/todo/1HTTP/1.1 200 AcceptedX-Api-Version: 1.1.0<more headers> {"todo": {}} # Unknown version $ curl -H "Accept-Version: ^3.0" http://localhost:3000/todo/1HTTP/1.1 400 Bad Request<more headers> Version ^3 is not supported
Version state variable
You can access the used version through the ctx.state:
router
Options
requestHeader
The default header is Accept-Version
, but you can change:
router;
responseHeader
The default header is X-Api-Version
, but you can change:
router;
routeParam
This module expects the path as v
followed by a single number:
- v1 is equivalent to ^1
- v2 is equivalent to ^2
- v11 is equivalent to ^11
The default param is version
, but you can change it:
router;
In order to make version optional and use the latest, use the ?
regex at the end:
router;
fallbackLatest
When the requested version is not found, the default response is an error, but you can choose to use the latest version:
router;
$ curl -i -H "Accept-Version: ^3.1.9" http://localhost:3000/todo/1HTTP/1.1 200 AcceptedX-Api-Version: 2.1.3<more headers> {"todo": {}}