-
Notifications
You must be signed in to change notification settings - Fork 7
/
index.js
107 lines (92 loc) · 2.85 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
/*
* http-rewrite-middleware
* https://github.com/viart/http-rewrite-middleware
*
* Copyright (c) 2014 Artem Vitiuk
* Licensed under the MIT license.
*/
'use strict';
function Rewriter (rules, options) {
options = options || {};
var nop = function () {};
if (options.silent) {
this.log = {
ok: nop,
error: nop,
verbose: nop
};
} else {
this.log = {
ok: console.log,
error: console.error,
verbose: options.verbose ? console.log : nop
};
}
this.rules = [];
(rules || []).forEach(this.registerRule, this);
}
Rewriter.prototype = {
registerRule: function (rule) {
var type = 'rewrite';
rule = rule || {};
if (this.isRuleValid(rule)) {
if (rule.redirect) {
rule.redirect = rule.redirect === 'permanent' ? 301 : 302;
type = 'redirect ' + rule.redirect;
}
this.rules.push({
from: new RegExp(rule.from),
to: rule.to,
redirect: rule.redirect
});
this.log.ok('Rewrite rule created for: [' + type.toUpperCase() + ': ' + rule.from + ' -> ' + rule.to + '].');
return true;
} else {
this.log.error('Wrong rule given.');
return false;
}
},
isRuleValid: function (rule) {
return rule.from && rule.to && typeof rule.from === 'string' && typeof rule.to === 'string';
},
resetRules: function () {
this.rules = [];
},
getRules: function () {
return this.rules;
},
dispatcher: function (req, res, next) {
var logger = this.log.verbose;
return function (rule) {
var toUrl,
fromUrl = req.url;
if (rule.from.test(req.url)) {
toUrl = req.url.replace(rule.from, rule.to);
if (!rule.redirect) {
req.url = toUrl;
next();
} else {
res.statusCode = rule.redirect;
res.setHeader('Location', toUrl);
res.end();
}
logger(
(rule.redirect ? 'redirect ' + rule.redirect : 'rewrite').toUpperCase() + ' > ' +
fromUrl + ' -> ' + toUrl + ' | By [' + rule.from + ' : ' + rule.to + ']'
);
return true;
}
};
},
getMiddleware: function () {
return function (req, res, next) {
if (!this.rules.length || !this.rules.some(this.dispatcher(req, res, next))) {
next();
}
}.bind(this);
}
};
module.exports.getMiddleware = function (rules, options) {
return (new Rewriter(rules, options)).getMiddleware();
};
module.exports.Rewriter = Rewriter;