Skip to content

Commit

Permalink
return lock id in .lock
Browse files Browse the repository at this point in the history
  • Loading branch information
calibr committed Jan 4, 2016
1 parent 04698c5 commit e3eff07
Show file tree
Hide file tree
Showing 3 changed files with 46 additions and 1 deletion.
16 changes: 16 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
2 changes: 1 addition & 1 deletion lib/warlock.js
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}
);

Expand Down
29 changes: 29 additions & 0 deletions test/warlock.js
Original file line number Diff line number Diff line change
Expand Up @@ -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();
});
});
});

0 comments on commit e3eff07

Please sign in to comment.