elliotttf / express-request-version

Express middleware for defining and validating a version.
1 stars 2 forks source link

Express Request Version

Greenkeeper badge

Build Status Coverage Status

This middleware allows a version property to be added to an express request object and provides basic version validation.

The resulting version will exist in the req.version property of all request objects.

In the case of semver routing a best effort is made to match the requested version with the supported versions. The original requested version will be placed in req.origVersion.

Usage

Version by path

Versions can be detected by path:

var setVersion = require('express-request-version').setByPath;
// Sets version for paths like /base/v1/thing.
app.use(setVersion('/base/'));

Version by semver path

Versions can be detected by semvers in the path:

var setVersion = require('express-request-version').setBySemverPath;
// Sets version for paths like /base/^v1.0.0/thing.
app.use(setVersion(['v1.0.0', 'v1.1.1', 'v2.0.0'], '/base/'));

Version by accept header

Versions can be detected by accept header:

var setVersion = require('express-request-version').setByAccept;
// Sets version for accept headers like application/vnd.myorg::1+xml.
app.use(setVersion('vnd.myorg', '::', '+xml'));
// Sets version for accept headers like application/vnd.myorg::1+json.
app.use(setVersion('vnd.myorg', '::');

Version by accept semver header

Versions can be detected by accept header with semvers:

var setVersion = require('express-request-version').setBySemverAccept;
// Sets version for accept headers like application/vnd.myorg::^1.0.0+xml.
app.use(setVersion(['v1.0.0', 'v1.1.1', 'v2.0.0'], 'vnd.myorg', '::', '+xml'));
// Sets version for accept headers like application/vnd.myorg::~1.0.0+json.
app.use(setVersion(['v1.0.0', 'v1.1.1', 'v2.0.0'], 'vnd.myorg', '::');

Version validation

You can define a set of supported versions, and raise an error if a request is made with an unsupported version:

var validateVersion = require('express-request-version').validateVersion;

// Will call next with an error if a request is made with a version other than
// one of those listed here.
app.use(validateVersion([ 'v1', 'v1.1', 'v1.1.1', 'v2' ]));

Helper function

In your controller files, you can add support for multiple versions by importing the multiVersion helper:

var multiVersion = require('express-request-version').multiVersion;
...
router.get(
'/myPath',
[other middleware],
multiVersion({
  '*': version1,
  'v0.1.0': version2,
}))

function version1(req, res) {
  res.send('This is version 1!')
}

function version2(req, res) {
  res.send('This is version 2!')
}

Note that a default version marked with '*' is mandatory.

API