forked from viart/http-rewrite-middleware
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
121 lines (106 loc) · 2.94 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
/*
* http-rewrite-middleware
* https://github.com/viart/http-rewrite-middleware
*
* Copyright (c) 2013 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,
delay : rule.delay || 0
} );
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, delay;
if( rule.from.test( req.url ) ) {
toUrl = req.url.replace( rule.from, rule.to );
delay = rule.delay ? rule.delay instanceof Function ? rule.delay( req ) : rule.delay : 0;
if( !rule.redirect ) {
req.url = toUrl;
if( delay ) {
setTimeout( function() {
next();
}, delay );
} else {
next();
}
} else {
res.statusCode = rule.redirect;
res.setHeader( 'Location', toUrl );
if( delay ) {
setTimeout( function() {
res.end();
}, delay );
} else {
res.end();
}
}
logger(
(rule.redirect ? 'redirect ' + rule.redirect : 'rewrite').toUpperCase() + ' > ' +
req.url + ' : ' + rule.from + ' -> ' + toUrl + ( rule.delay ? ', delayed : ' + rule.delay + 'ms' : '' )
);
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;