Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Modify put function to support a time that exceeds setTimeout's maximum time #88

Open
wants to merge 6 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 24 additions & 5 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -30,13 +30,32 @@ function Cache () {
expire: time + Date.now()
};

if (!isNaN(record.expire)) {
var extendedTimeout = function(expiresMs) {
// Max time that setTimeOut can handle (in milliseconds)
var maxTimeoutMs = 2147483647;
// If the time passed in to extendedTimeout is too large for setTimeout, the
// maxTimeoutMs has to be used instead.
var timeoutMs = (expiresMs > maxTimeoutMs) ? maxTimeoutMs : expiresMs;


record.timeout = setTimeout(function() {
_del(key);
if (timeoutCallback) {
timeoutCallback(key, value);
// Calculates how much time is left till the cached data expires
var timeLeft = expiresMs - timeoutMs;

// When timeLeft is <= 0, then the cached data has expired
if (timeLeft <= 0) {
_del(key);
if (timeoutCallback) {
timeoutCallback(key, value);
}
} else {
extendedTimeout(timeLeft);
}
}.bind(this), time);
}.bind(this), timeoutMs);
};

if (!isNaN(record.expire)) {
extendedTimeout(time);
}

_cache[key] = record;
Expand Down
11 changes: 11 additions & 0 deletions test.js
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,17 @@ describe('node-cache', function() {
expect(spy).to.have.been.calledOnce.and.calledWith('key', 'value');
});

it('should cause the timeout callback to fire once 30 days later', function() {
var spy = sinon.spy();
var thirtyDays = 2592000000;
var timeoutMax = 2147483648;
cache.put('key', 'value', thirtyDays, spy);
clock.tick(timeoutMax);
expect(spy).to.not.have.been.called;
clock.tick(thirtyDays-timeoutMax);
expect(spy).to.have.been.calledOnce.and.calledWith('key', 'value')
});

it('should override the timeout callback on a new put() with a different timeout callback', function() {
var spy1 = sinon.spy();
var spy2 = sinon.spy();
Expand Down