-
Notifications
You must be signed in to change notification settings - Fork 2
/
index.js
41 lines (33 loc) · 1.05 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
const Scripty = require('node-redis-scripty');
function makeRedisKey(key) {
return key + ':throttle';
}
module.exports = function(redis) {
const scripty = new Scripty(redis);
function throttle(key, throttleFn, ttl, noRetry /* Private */) {
scripty.loadScriptFile(
'claimThrottleLock',
`${__dirname}/lua/claimThrottleLock.lua`,
(err, claimThrottleLock) => {
if (err) return void throttleFn(err);
claimThrottleLock.run(1, makeRedisKey(key), ttl, (err, expiresIn) => {
if (err) return void throttleFn(err);
// If being throttled, wait for its expiration and try to run once more.
if (expiresIn >= 0) {
if (!noRetry) {
setTimeout(() => throttle(key, throttleFn, ttl, true /* No retry */), expiresIn);
}
} else {
throttleFn();
}
});
}
);
}
// Create an alias.
throttle.call = throttle;
throttle.cancel = function(key, callback) {
redis.del(makeRedisKey(key), callback);
};
return throttle;
};