forked from errorception/redis-lock
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
62 lines (50 loc) · 1.56 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
"use strict";
var util = require('util');
var defaultTimeout = 5000;
var promisify = util.promisify || function(x) { return x; };
function acquireLock(client, lockName, timeout, retryDelay, onLockAcquired) {
function retry() {
setTimeout(function() {
acquireLock(client, lockName, timeout, retryDelay, onLockAcquired);
}, retryDelay);
}
var lockTimeoutValue = (Date.now() + timeout + 1);
client.set(lockName, lockTimeoutValue, 'PX', timeout, 'NX', function(err, result) {
if(err || result === null) return retry();
onLockAcquired(lockTimeoutValue);
});
}
module.exports = function(client, retryDelay) {
if(!(client && client.setnx)) {
throw new Error("You must specify a client instance of http://github.com/mranney/node_redis");
}
retryDelay = retryDelay || 50;
function lock(lockName, timeout, taskToPerform) {
if(!lockName) {
throw new Error("You must specify a lock string. It is on the redis key `lock.[string]` that the lock is acquired.");
}
if(!taskToPerform) {
taskToPerform = timeout;
timeout = defaultTimeout;
}
lockName = "lock." + lockName;
acquireLock(client, lockName, timeout, retryDelay, function(lockTimeoutValue) {
taskToPerform(promisify(function(done) {
done = done || function() {};
if(lockTimeoutValue > Date.now()) {
client.del(lockName, done);
} else {
done();
}
}));
});
}
if(util.promisify) {
lock[util.promisify.custom] = function(lockName, timeout) {
return new Promise(function(resolve) {
lock(lockName, timeout || defaultTimeout, resolve);
});
}
}
return lock;
};