-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy pathmodule.js
56 lines (45 loc) · 1.29 KB
/
module.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
async function redirectModule(moduleOptions) {
const defaults = {
rules: [],
onDecode: (req, res, next) => decodeURI(req.url),
onDecodeError: (error, req, res, next) => next(error)
}
const options = {
...defaults,
...await parseOptions(this.options.redirect),
...await parseOptions(moduleOptions)
}
if (this.options.mode === 'spa') {
return this.extendRoutes((routes) => {
options.rules.forEach((route) => {
routes.push({
path: route.path || route.from,
redirect: route.redirect || route.to
})
})
})
}
options.rules = options.rules.map(rule => ({ ...rule, from: new RegExp(rule.from) }))
const middleware = require('./middleware.js')(options)
this.addServerMiddleware(middleware)
}
async function parseOptions(options) {
if (typeof options === 'function') {
options = await options()
}
if (Object.keys(options).length === 0) {
return []
}
if (Array.isArray(options)) {
return { rules: options }
}
if (typeof options.rules === 'function') {
options.rules = await options.rules()
}
if (options.rules && !Array.isArray(options.rules)) {
options.rules = [options.rules]
}
return options
}
module.exports = redirectModule
module.exports.meta = require('../package.json')