-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
53 lines (45 loc) · 1.21 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
'use strict'
const {STATUS_CODES} = require('http')
const redirects = require('./redirects.json')
const uriMatch = ({request}) => {
try {
const {uri, querystring} = request
const url = querystring ? `${uri}?${querystring}` : uri
const match = redirects.filter(redirect => url.match(redirect.source))
// If there's no match, don't bother, just return an empty object
if (!match.length) {
return {}
}
const {to, status = 301} = match.shift()
return {to, status}
} catch (e) {
console.log('uriMatch: Error', e)
// If there's an error, return an empty object
return {}
}
}
exports.handler = (event, context, callback) => {
const {cf} = event.Records[0]
const {request} = cf
const {to, status} = uriMatch({request})
if (!to) {
// Continue the response
return callback(null, cf.response || request)
}
const response = {
status: String(status),
statusDescription: STATUS_CODES[status],
headers: {
'content-type': [{
key: 'Content-Type',
value: 'text/plain; charset=UTF-8'
}],
location: [{
key: 'Location',
value: to
}]
}
}
return callback(null, response)
}
exports.uriMatch = uriMatch