/
mapped.js
59 lines (44 loc) · 1.34 KB
/
mapped.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
57
58
59
var url = require('url')
module.exports = function(mappedPaths) {
var reverseMap = Object.create(null)
if (typeof mappedPaths !== 'object') {
throw new Error('A hash map of paths is required')
}
Object.keys(mappedPaths).forEach(function(url) {
reverseMap[mappedPaths[url]] = url
})
return {
/**
* This is intended to be exported as a helper for the view layer
*/
versionPath: function(urlPath) {
if (!Array.isArray(urlPath)) {
return mappedPaths[urlPath.toString()] || urlPath
}
return urlPath.map(function(singleUrl) {
return mappedPaths[singleUrl.toString()] || singleUrl
})
},
modifyMap: function(someMappedPaths) {
Object.keys(someMappedPaths).forEach(function(url) {
mappedPaths[url] = someMappedPaths[url]
})
// regenerate reverseMap. DRY?
Object.keys(mappedPaths).forEach(function(url) {
reverseMap[mappedPaths[url]] = url
})
},
middleware: function(req, res, next) {
// We only do this on GET and HEAD requests
if ('GET' !== req.method && 'HEAD' !== req.method) {
return next()
}
var parsedUrl = url.parse(req.url)
, mappedUrl = reverseMap[parsedUrl.pathname]
if (mappedUrl) {
req.url = mappedUrl + (parsedUrl.search || '')
}
next()
}
}
}