Skip to content

Commit

Permalink
implement expiration via settimeout
Browse files Browse the repository at this point in the history
  • Loading branch information
cmawhorter committed Aug 28, 2014
1 parent f0eea30 commit 5afd85b
Show file tree
Hide file tree
Showing 3 changed files with 17 additions and 39 deletions.
20 changes: 16 additions & 4 deletions lib/keys.js
Expand Up @@ -48,9 +48,19 @@ exports.expire = function (mockInstance, key, seconds, callback) {

if (obj) {

mockInstance.storage[key].expires = seconds;
var now = new Date().getTime();
var milli = (seconds*1000);

if (mockInstance.storage[key]._expire) {
clearTimeout(mockInstance.storage[key]._expire);
}

mockInstance.storage[key].expires = new Date(now + milli);
mockInstance.storage[key]._expire = setTimeout(function() {
delete mockInstance.storage[key];
}, milli);

result = 1;
mockInstance._toggleExpireCheck(true);
}

mockInstance._callCallback(callback, null, result);
Expand All @@ -67,8 +77,10 @@ exports.ttl = function (mockInstance, key, callback) {

if (obj) {

var seconds = mockInstance.storage[key].expires;
if (seconds) {
var now = new Date().getTime();
var expires = mockInstance.storage[key].expires instanceof Date ? mockInstance.storage[key].expires.getTime() : -1;
var seconds = (expires - now) / 1000;
if (seconds > 0) {
result = seconds;
} else {
result = -1;
Expand Down
34 changes: 0 additions & 34 deletions lib/redis-mock.js
Expand Up @@ -18,40 +18,6 @@ function RedisMock() {

var self = this;

this._expireCheck = function () {
var found = false;
for (var s in self.storage) {
if (self.storage[s].expires > 0) {
self.storage[s].expires--;
found = true;
}
else if (self.storage[s].expires == 0) {
delete self.storage[s];
found = true;
}
}

if (!found) {
self._toggleExpireCheck(false);
}
};

this._toggleExpireCheck = function (toggle) {
if (!toggle) {
if (this._expireLoop) {
clearInterval(this._expireLoop);
this._expireLoop = null;
}
}
else {
if (!this._expireLoop) {
this._expireLoop = setInterval(this._expireCheck, 1000);
}

}

};

/**
* Helper function to launch the callback(err, reply)
* on the next process tick
Expand Down
2 changes: 1 addition & 1 deletion test/redis-mock.keys.test.js
Expand Up @@ -171,7 +171,7 @@ describe("ttl", function () {

result.should.equal(1);

clock.tick(500);
clock.tick(5000);
r.ttl("test", function (err, ttl) {
if (err) {
done(err);
Expand Down

0 comments on commit 5afd85b

Please sign in to comment.