This repository has been archived by the owner on Aug 6, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
216 lines (162 loc) · 5.75 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
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
const http = require('http');
const http2 = require('http2');
const https = require('https');
/**
* Rewrite condition object
* @typedef {Object} RewriteCond
* @property {String|RegExp|Function<Boolean>} match Matching rule
* @property {String} to Rewrite target
*/
/** Not really good rewriter for Fastify */
class CrutchyRewriter {
/**
* Creates a Rewriter instance
* @param {Array<RewriteCond>} [rewrites] Rewrite rules
*/
constructor(rewrites) {
/**
* Rewrite conditions
* @type {Object}
*/
this.conditions = {
/**
* Exact matching hashmap
* @type {Map}
*/
exact: new Map(),
/**
* Regexp store
* @type {Array<RegExp>}
*/
regexps: [],
/**
* Regexp values store
* @type {Array<String>}
*/
rgvalues: [],
/**
* Comparators store
* @type {Array<Function<Boolean>>}
*/
comparators: [],
/**
* Comparated values store
* @type {Array<String>}
*/
cpvalues: [],
};
// Check is rewrite conditions are passed
if (typeof rewrites === 'undefined')
return;
// Check is rewrite conditions passed as array
if (!Array.isArray(rewrites))
throw new TypeError(`Rewrites conditions in constructor must be an Array, but ${typeof rewrites} given`);
// Apply them
rewrites.forEach(({ match, to }) => this.add(match, to));
}
/**
* Apply new condition into rewrite conditions buffer
* @param {String|RegExp|Function<Boolean>} match Matching condition for rewrite
* @param {String} to Rewrite target
* @returns {Boolean} Returns true, if succeed
* @throws {TypeError} Will throw an error if "match" or "to" incorrect
*/
add(match, to) {
if (typeof to !== 'string')
throw new TypeError(`Rewriting "to" directive must be a string, but ${typeof to} given`);
switch (typeof match) {
// Regular expression
case 'object':
if (!(match instanceof RegExp))
throw new TypeError('Given "match" criteria is an object, but is not a regular expression');
this.conditions.regexps.push(match);
this.conditions.rgvalues.push(to);
return true;
// Compare functions
case 'function':
this.conditions.comparators.push(match);
this.conditions.cpvalues.push(to);
return true;
// Exact match
case 'string':
if (match.length === 0)
throw new Error('Match condition string can\'t be empty');
this.conditions.exact.set(match, to);
return true;
// Unknown stuff
default:
throw new TypeError(`Unsupported rewrite "from" condition given: ${typeof match}`);
}
}
/**
* Matches original URL with rewrite replacement
* @param {String} url Original URL
* @returns {String|null} Returns target URL if related rewrite condition exists, null otherwise
*/
matchCondition(url) {
if (typeof url !== 'string')
throw new TypeError(`#matchCondition expects to receive URL as string, but ${typeof url} is given`);
// Matching with exact rewrite conditions first
const rewrite = this.conditions.exact.get(url);
if (typeof rewrite === 'string')
return rewrite;
// Matching with comparators
for (let idx = 0, len = this.conditions.comparators.length; idx < len; idx += 1)
// Call each comparator until the first match
if (this.conditions.comparators[idx](url))
return this.conditions.cpvalues[idx];
// Matching with regular expressions
for (let idx = 0, len = this.conditions.regexps.length; idx < len; idx += 1)
// Call each comparator until the first match
if (this.conditions.regexps[idx].test(url))
return this.conditions.rgvalues[idx];
return null;
}
/**
* Returns HTTP handler with injected rewriter
* @param {Function<Object,Object>} handler Fastify default handler
* @returns {Function<Object,Object>} Handler with rewriter proxy
*/
createInterceptHandler(handler) {
if (typeof handler !== 'function')
throw new TypeError(`Intercept hadler must be a function, but ${typeof handler} given`);
return (req, res) => {
const rewrite = this.matchCondition(req.url);
if (!rewrite) {
handler(req, res);
return;
}
req.url = rewrite;
handler(req, res);
};
}
/**
* Returns our serverFactory binded to this class context
* @returns {Object} Native HTTP server
*/
createServerFactory() {
return this.serverFactory.bind(this);
}
/**
* Implementation of Fastify serverFactory interface
* @param {Function<Object,Object>} handler Fastify HTTP handler
* @param {Object} [opts] Fastify options object
* @returns {Object} Native HTTP server
*/
serverFactory(handler, opts) {
if (typeof handler !== 'function')
throw new TypeError(`HTTP handler must be a function, but ${typeof handler} given`);
if (typeof opts !== 'undefined' && typeof opts !== 'object')
throw new TypeError(`Server factory "opts" argument must be an object or undefined, but ${typeof opts} given`);
// HTTP/1.1 Plain
if (typeof opts === 'undefined' || (!opts.http2 && !opts.https))
return http.createServer(this.createInterceptHandler(handler));
if (!opts.http2 && opts.https)
return https.createServer(opts.https, this.createInterceptHandler(handler));
// HTTP/2
if (opts.https)
return http2.createSecureServer(opts.https, this.createInterceptHandler(handler));
return http2.createServer(this.createInterceptHandler(handler));
}
}
module.exports = CrutchyRewriter;