-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathindex.js
109 lines (92 loc) · 2.83 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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
/**
* Redirects naked(root domain) requests to www or its reverse.
*
* @author GONZO <[email protected]>
*/
const subdomainParser = (function () {
const { parseDomain } = require('parse-domain')
const parsedDomain = {}
return {
get: function (hostname) {
// Cache, Touch
if (parsedDomain[hostname] === undefined) {
try {
const ps = parseDomain(hostname)
parsedDomain[hostname] = [ps.subDomains.join('.'), ps.domain + '.' + ps.topLevelDomains.join('.')]
} catch (e) {
parsedDomain[hostname] = [null, null]
}
}
return parsedDomain[hostname]
}
}
}())
module.exports = function (reverse, subDomain, status) {
let options = {}
if (arguments.length === 1 && typeof arguments[0] === 'object') {
options = arguments[0]
} else {
options = {
reverse: reverse,
subDomain: subDomain,
status: status
}
}
if (options.except) {
if (typeof options.except === 'string') {
options.except = [options.except]
}
// Assertion
if (typeof options.except.length !== 'number') {
throw new Error('Except option must be set with an array or string.')
}
let UrlPattern
try {
UrlPattern = require('url-pattern')
} catch (e) {
console.error(e)
throw new Error('The third party module `url-pattern` is required.')
}
for (let i = 0; i < options.except.length; i++) {
options.except[i] = new UrlPattern(options.except[i])
}
}
return function (req, res, next) {
const domain = subdomainParser.get(req.hostname)
options.subDomain = options.subDomain || 'www'
if (options.except) {
for (let i = 0; i < options.except.length; i++) {
if (options.except[i].match(req.url)) {
return next()
}
}
}
if (typeof (options.reverse) === 'string' && options.subDomain === undefined) {
options.subDomain = options.reverse
options.reverse = false
}
if (options.status === undefined) {
options.status = 302
}
if (typeof (options.protocol) === 'string') {
options.protocol = options.protocol // eslint-disable-line
} else if (typeof (options.https) === 'boolean' && options.https) {
options.protocol = 'https'
} else {
options.protocol = req.protocol
}
let redirectTo = null
if (domain[0] === '' && !options.reverse) {
redirectTo = `${options.protocol}://${options.subDomain}.${domain[1]}${req.url}`
} else if (domain[0] === options.subDomain && options.reverse) {
redirectTo = `${options.protocol}://${domain[1]}${req.url}`
} else if (options.protocol !== req.protocol) {
redirectTo = `${options.protocol}://${req.hostname}${req.url}`
}
if (redirectTo !== null) {
res.redirect(options.status, redirectTo)
return
}
return next()
}
}