|
| 1 | +var async = require('async'); |
| 2 | + |
| 3 | +/** |
| 4 | + * Module that lets you specify a hiearchy of caches. |
| 5 | + */ |
| 6 | +var multi_caching = function(caches) { |
| 7 | + var self = {}; |
| 8 | + if (!Array.isArray(caches)) { throw new Error('multi_caching requires an array of caches'); } |
| 9 | + |
| 10 | + function get_from_highest_priority_cache(key, cb) { |
| 11 | + var i = 0; |
| 12 | + async.forEachSeries(caches, function(cache, async_cb) { |
| 13 | + cache.store.get(key, function(err, result) { |
| 14 | + if (err) { return cb(err); } |
| 15 | + if (result) { |
| 16 | + // break out of async loop. |
| 17 | + return cb(err, result, i); |
| 18 | + } |
| 19 | + |
| 20 | + i += 1; |
| 21 | + async_cb(err); |
| 22 | + }); |
| 23 | + }, cb); |
| 24 | + } |
| 25 | + |
| 26 | + function set_in_multiple_caches(caches, key, value, cb) { |
| 27 | + async.forEach(caches, function(cache, async_cb) { |
| 28 | + cache.store.set(key, value, async_cb); |
| 29 | + }, cb); |
| 30 | + }; |
| 31 | + |
| 32 | + /** |
| 33 | + * Wraps a function in one or more caches. |
| 34 | + * Has same API as regular caching module. |
| 35 | + * |
| 36 | + * If a key doesn't exist in any cache, it gets set in all caches. |
| 37 | + * If a key exists in a high-priority (e.g., first) cache, it gets returned immediately |
| 38 | + * without getting set in other lower-priority caches. |
| 39 | + * If a key doesn't exist in a higher-priority cache but exists in a lower-priority |
| 40 | + * cache, it gets set in all higher-priority caches. |
| 41 | + */ |
| 42 | + self.run = function(key, work, cb) { |
| 43 | + get_from_highest_priority_cache(key, function(err, result, index) { |
| 44 | + if (err) { return cb(err); } |
| 45 | + if (result) { |
| 46 | + var caches_to_set = caches.slice(0, index); |
| 47 | + set_in_multiple_caches(caches_to_set, key, result, function(err) { |
| 48 | + return cb(err, result); |
| 49 | + }); |
| 50 | + } else { |
| 51 | + work(function() { |
| 52 | + var work_args = Array.prototype.slice.call(arguments, 0); |
| 53 | + |
| 54 | + set_in_multiple_caches(caches, key, work_args[1], function(err) { |
| 55 | + cb.apply(null, work_args); |
| 56 | + }); |
| 57 | + }); |
| 58 | + } |
| 59 | + }); |
| 60 | + }; |
| 61 | + |
| 62 | + self.set = function(key, value, cb) { |
| 63 | + set_in_multiple_caches(caches, key, value, cb); |
| 64 | + }; |
| 65 | + |
| 66 | + self.get = function(key, cb) { |
| 67 | + get_from_highest_priority_cache(key, cb); |
| 68 | + }; |
| 69 | + |
| 70 | + self.del = function(key, cb) { |
| 71 | + async.forEach(caches, function(cache, async_cb) { |
| 72 | + cache.store.del(key, async_cb); |
| 73 | + }, cb); |
| 74 | + }; |
| 75 | + |
| 76 | + return self; |
| 77 | +}; |
| 78 | + |
| 79 | +module.exports = multi_caching; |
0 commit comments