/
basic.js
56 lines (43 loc) · 1.24 KB
/
basic.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
47
48
49
50
51
52
53
54
55
56
var path = require('path')
module.exports = function(version) {
if (!version) {
throw new Error('version is required')
}
function versionSinglePath(urlPath) {
urlPath = urlPath.toString()
var pos = urlPath.lastIndexOf('/')
if (pos !== -1) {
return path.normalize(urlPath.substring(0, pos) + '/' + version + urlPath.substring(pos)).replace(/\\/g, '/')
} else {
return urlPath
}
}
return {
/**
* This is intended to be exported as a helper for the view layer
*/
versionPath: function(urlPath) {
if (!Array.isArray(urlPath)) {
return versionSinglePath(urlPath)
}
return urlPath.map(function(singleUrl) {
return versionSinglePath(singleUrl)
})
},
middleware: function(req, res, next) {
if (req.method !== 'GET') {
return next()
}
// Ensure version is a string
version = '' + version
var vPos = req.url.indexOf(version)
// If version isn't in path then move on.
if (vPos === -1) {
return next()
}
// Rebuild the URL without the version and set the request url.
req.url = req.url.substring(0, vPos - 1) + req.url.substring(vPos + version.length)
next()
}
}
}