-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmain.js
More file actions
91 lines (88 loc) · 2.46 KB
/
main.js
File metadata and controls
91 lines (88 loc) · 2.46 KB
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
/* eslint-disable node/no-unsupported-features/es-syntax */
// REFERENCES
// https://tools.ietf.org/html/rfc7231#section-7.1.2
export const REDIRECT_STATUS_CODES = {
FOUND: 302,
MOVED_PERMANENTLY: 301,
PERMANENT_REDIRECT: 308,
SEE_OTHER: 303,
TEMPORARY_REDIRECT: 307,
}
export const rewriteHandler = ({ rules = [] } = { rules: [] }) => {
const compiledRules = []
const handle = ({ request, response }) => {
if (request.aborted === true || response.writableEnded === true) {
return
}
let statusCode
for (const rule of compiledRules) {
if ((rule.method !== undefined && rule.method !== request.method) || (rule.host !== undefined && rule.host !== request.headers.host)) {
continue
}
let isReplaced = false
if (rule.replacementFunction === undefined) {
if (rule.pattern.test(request.url) === true) {
request.url = request.url.replace(rule.pattern, rule.replacement)
isReplaced = true
}
} else {
const url = rule.replacementFunction(request.url)
if (url !== undefined) {
request.url = url
isReplaced = true
}
}
if (isReplaced === true) {
statusCode = rule.statusCode
if (rule.isBreak === true) {
break
}
}
}
if (statusCode !== undefined) {
response
.writeHead(statusCode, {
Location: request.url,
})
.end()
}
}
const compilePattern = ({ isCaseSensitive, isUnicode, pattern }) => {
let flags = ''
if (isCaseSensitive === true) {
flags += 'i'
}
if (isUnicode === true) {
flags += 'u'
}
return new RegExp(pattern, flags)
}
const push = ({ host, isBreak = false, isCaseSensitive = false, isUnicode = false, method, pattern, replacement, replacementFunction, statusCode }) => {
if ((pattern === undefined || replacement === undefined) && replacementFunction === undefined) {
throw Error('The fields pattern and replacement can not be undefined while replacementFunction one is undefined')
}
compiledRules.push({
host,
isBreak,
method,
pattern:
pattern === undefined
? undefined
: compilePattern({
isCaseSensitive,
isUnicode,
pattern,
}),
replacement,
replacementFunction,
statusCode,
})
}
for (const rule of rules) {
push(rule)
}
return {
handle,
push,
}
}