-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy pathindex.js
46 lines (38 loc) · 1.34 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
'use strict'
const semver = require('semver')
const { RouteVersionUnmatchedError } = require('./errors')
class versionRouter {
static route (versionsMap = new Map(), options = new Map()) {
return (req, res, next) => {
var versionArray = []
for (let [versionKey, versionRouter] of versionsMap) {
versionArray.push(versionKey)
if (this.checkVersionMatch(req.version, versionKey)) {
return versionRouter(req, res, next)
}
}
if (options.useMaxVersion) {
const maxVersion = semver.maxSatisfying(versionArray, req.version)
if (maxVersion) {
for (let [versionKey, versionRouter] of versionsMap) {
if (this.checkVersionMatch(maxVersion, versionKey)) {
return versionRouter(req, res, next)
}
}
}
}
const defaultRoute = this.getDefaultRoute(versionsMap)
if (defaultRoute) {
return defaultRoute(req, res, next)
}
return next(new RouteVersionUnmatchedError(`${req.version} doesn't match any versions`))
}
}
static checkVersionMatch (requestedVersion, routeVersion) {
return semver.valid(requestedVersion) && semver.satisfies(requestedVersion, routeVersion)
}
static getDefaultRoute (options = new Map()) {
return options.get('default')
}
}
module.exports = versionRouter