diff --git a/README.md b/README.md index 4171653..4043f43 100644 --- a/README.md +++ b/README.md @@ -57,6 +57,22 @@ var maxAttempts = 4; // Max number of times to try setting the lock before error var wait = 1000; // Time to wait before another attempt if lock already in place warlock.optimistic(key, ttl, maxAttempts, wait, function(err, unlock) {}); +// unlock using the lock id +var key = 'test-lock-2'; +var ttl = 10000; +var lockId; + +warlock.lock(key, ttl, function(err, _, id) { + lockId = id; +}); + +// each client who knows the lockId can release the lock +warlock.unlock(key, lockId, function(err, result) { + if(result == 1) { + // unlocked successfully + } +}); + ``` ## ProTips diff --git a/lib/warlock.js b/lib/warlock.js index 6e6fb6e..c38b688 100644 --- a/lib/warlock.js +++ b/lib/warlock.js @@ -36,7 +36,7 @@ module.exports = function(redis){ var unlock = warlock.unlock.bind(warlock, key, id); if (!lockSet) unlock = false; - return cb(err, unlock); + return cb(err, unlock, id); } ); diff --git a/test/warlock.js b/test/warlock.js index 973d0b4..bf8e06b 100644 --- a/test/warlock.js +++ b/test/warlock.js @@ -44,3 +44,32 @@ describe('locking', function() { }); }); }); + +describe('unlocking with id', function() { + var lockId; + + it('sets lock and gets lock id', function(done) { + warlock.lock('customlock', 20000, function(err, unlock, id) { + should.not.exists(err); + id.should.type("string"); + lockId = id; + done(); + }); + }); + + it('does not unlock with wrong id', function(done) { + warlock.unlock('customlock', "wrongid", function(err, result) { + should.not.exists(err); + result.should.equal(0); + done(); + }); + }); + + it('unlocks', function(done) { + warlock.unlock('customlock', lockId, function(err, result) { + should.not.exists(err); + result.should.equal(1); + done(); + }); + }); +});