Skip to content

Commit 2b60fae

Browse files
authored
Merge pull request jaredwray#65 from philippeauriach/feature/dynamic-cache-ttl
Feature/dynamic cache ttl
2 parents fdb929a + 2770f95 commit 2b60fae

File tree

2 files changed

+31
-0
lines changed

2 files changed

+31
-0
lines changed

lib/caching.js

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -113,6 +113,10 @@ var caching = function(args) {
113113
return;
114114
}
115115

116+
if (options && typeof options.ttl === 'function') {
117+
options.ttl = options.ttl(data);
118+
}
119+
116120
self.store.set(key, data, options, function(err) {
117121
if (err && (!self.ignoreCacheErrors)) {
118122
callbackFiller.fill(key, err);

test/caching.unit.js

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -360,6 +360,33 @@ describe("caching", function() {
360360
});
361361
});
362362

363+
context("ttl function", function() {
364+
beforeEach(function() {
365+
sinon.spy(memoryStoreStub, 'set');
366+
});
367+
368+
afterEach(function() {
369+
memoryStoreStub.set.restore();
370+
});
371+
372+
it("when a ttl function is passed in", function(done) {
373+
opts = {
374+
ttl: function(widget) {
375+
assert.deepEqual(widget, {name: name});
376+
return 0.2;
377+
}
378+
};
379+
cache.wrap(key, function(cb) {
380+
methods.getWidget(name, cb);
381+
}, opts, function(err, widget) {
382+
checkErr(err);
383+
assert.deepEqual(widget, {name: name});
384+
sinon.assert.calledWith(memoryStoreStub.set, key, {name: name}, {ttl: 0.2});
385+
done();
386+
});
387+
});
388+
});
389+
363390
context("when result is already cached", function() {
364391
function getCachedWidget(name, cb) {
365392
cache.wrap(key, function(cacheCb) {

0 commit comments

Comments
 (0)