Permalink
Browse files

Add ability to manually clear cache.

  • Loading branch information...
1 parent 8a386db commit 7894854b12712f7049423179fe5f56c4ac87c436 @mape committed Aug 23, 2011
Showing with 30 additions and 2 deletions.
  1. +19 −0 example.js
  2. +11 −2 lib/caching.js
View
19 example.js
@@ -0,0 +1,19 @@
+var Caching = require('./lib/caching');
+var cache = new Caching('memory'); /* use 'memory' or 'redis' */
+
+var key = 'a-key-'+Date.now();
+var ttl = 30*1000;
+setInterval(function() {
+ cache(key, ttl, function(passalong) {
+ console.log('This closure runs when nothing is in cache.');
+ setTimeout(function() {
+ passalong(null, 'cached result with '+ttl+'ms ttl');
+ }, 1000);
+ }, function(err, results) {
+ // This callback will be reused each call
+ console.log(new Date().toString().match(/..:..:../)+' - Results:', results);
+ });
+}, 100);
+
+// If you want to clear the cache manually you can use:
+cache.remove(key);
View
13 lib/caching.js
@@ -12,6 +12,9 @@ var MemoryStore = function() {
}, ttl);
}
}
+ , 'remove': function(key) {
+ delete cache[key];
+ }
};
};
var RedisStore = function() {
@@ -30,6 +33,9 @@ var RedisStore = function() {
redisClient.set(key, JSON.stringify(result));
}
}
+ , 'remove': function(key) {
+ redisClient.DEL(key);
+ }
};
};
@@ -54,7 +60,8 @@ module.exports = Caching = function Caching(store) {
}
var queues = {};
- return function(key, ttl, workCallback, callback) {
+
+ var cacher = function(key, ttl, workCallback, callback) {
store.get(key, function(err, storageData) {
if (!err && storageData) {
callback.apply(null, storageData);
@@ -72,5 +79,7 @@ module.exports = Caching = function Caching(store) {
});
}
});
- };
+ }
+ cacher.remove = store.remove;
+ return cacher;
};

0 comments on commit 7894854

Please sign in to comment.