From b579f8acb78b8b09a117e97a1ea47096f06a37a7 Mon Sep 17 00:00:00 2001 From: Jonathan Muller Date: Mon, 1 Jun 2015 13:16:40 +0200 Subject: [PATCH] Stores can override isCacheableValue + tests This is usefull ie for redis cache where null is returned when cache data does not exists In other stores, null can still be stored and undefined used when data does not exist Each store can implement its own custom method --- examples/redis_example/redis_store.js | 4 ++++ lib/caching.js | 2 ++ test/caching.unit.js | 21 +++++++++++++++++++++ 3 files changed, 27 insertions(+) diff --git a/examples/redis_example/redis_store.js b/examples/redis_example/redis_store.js index 247eca5..b6210a4 100644 --- a/examples/redis_example/redis_store.js +++ b/examples/redis_example/redis_store.js @@ -110,6 +110,10 @@ function redisStore(args) { }); }; + self.isCacheableValue = function(value) { + return value !== null && value !== undefined; + }; + return self; } diff --git a/lib/caching.js b/lib/caching.js index 959b7e9..f98bb3a 100644 --- a/lib/caching.js +++ b/lib/caching.js @@ -34,6 +34,8 @@ var caching = function(args) { if (typeof args.isCacheableValue === 'function') { self._isCacheableValue = args.isCacheableValue; + } else if (typeof self.store.isCacheableValue === 'function') { + self._isCacheableValue = self.store.isCacheableValue; } else { self._isCacheableValue = function(value) { return value !== undefined; diff --git a/test/caching.unit.js b/test/caching.unit.js index 6f52e85..227e4f9 100644 --- a/test/caching.unit.js +++ b/test/caching.unit.js @@ -707,4 +707,25 @@ describe("caching", function() { }); }); }); + + describe("overloading with custom store", function() { + it("allows us to override isCacheableValue", function(done) { + var store = memoryStore.create({ttl: defaultTtl}); + var onlyOne = true; + store.isCacheableValue = function(result) { + if (onlyOne) { + onlyOne = false; + done(); + } + return result !== undefined; + }; + cache = caching({store: store}); + cache.wrap(key, function(cb) { + methods.getWidget(name, cb); + }, function(err, widget) { + checkErr(err); + assert.deepEqual(widget, {name: name}); + }); + }); + }); });