-
Notifications
You must be signed in to change notification settings - Fork 6
/
throttle.js
101 lines (83 loc) · 3.14 KB
/
throttle.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
module.exports = function(RED) {
"use strict";
function throttle(config) {
RED.nodes.createNode(this, config);
var node = this;
// config
this.throttleType = config.throttleType || "time";
this.timeLimitType = config.timeLimitType || "seconds";
this.timeLimit = Number(config.timeLimit || 0);
this.countLimit = Number(config.countLimit || 0);
this.blockSize = Number(config.blockSize || 0);
this.locked = config.locked || false;
// helpers
this.time = this.locked ? Math.floor(Date.now()) : 0;
this.count = this.locked ? 1 : 0;
this.block = this.locked ? this.blockSize + 1 : 0;
this.reset = !!this.locked;
// calculate time limit in milliseconds
if( this.timeLimitType === "hours" ) {
this.timeLimit *= 60 * 60 * 1000;
}
else if( this.timeLimitType === "minutes" ) {
this.timeLimit *= 60 * 1000;
}
else if( this.timeLimitType === "seconds" ) {
this.timeLimit *= 1000;
}
this.on("input", function(msg) {
// throttle by time
if( node.throttleType === "time" ) {
if( isNaN(node.timeLimit) || !isFinite(node.timeLimit) ) {
return this.error("time limit is not numeric", msg);
}
var now = Math.floor(Date.now());
if( node.time + node.timeLimit < now ) {
node.time = now;
node.send(msg);
}
}
// throttle by count
else if( node.throttleType === "count" ) {
if( isNaN(node.countLimit) || !isFinite(node.countLimit) ) {
return this.error("count limit is not numeric", msg);
}
++node.count;
if( node.count >= node.countLimit ) {
node.count = 0;
}
if( node.countLimit === 0 || node.countLimit === 1 || node.count === 1 ) {
node.send(msg);
}
}
// throttle by block size
else if( node.throttleType === "block" ) {
if( isNaN(node.blockSize) || !isFinite(node.blockSize) ) {
return this.error("block size is not numeric", msg);
}
++node.block;
if( node.block <= node.blockSize ) {
node.send(msg);
}
else if( msg.reset ) {
node.block = 0;
}
}
// throttle by reset
else if( node.throttleType === "reset" ) {
if( !node.reset ) {
node.reset = true;
node.send(msg);
}
else if( msg.reset ) {
node.reset = false;
}
}
// unknown throttle type
else {
this.error("unknown throttle type '" + node.throttleType + "'", msg);
}
});
}
RED.nodes.registerType("throttle", throttle);
};