|
|
@ -7,6 +7,8 @@ var multi_caching = function (caches) { |
|
|
|
var self = {}; |
|
|
|
if (!Array.isArray(caches)) { throw new Error('multi_caching requires an array of caches'); } |
|
|
|
|
|
|
|
self.queues = {}; |
|
|
|
|
|
|
|
function get_from_highest_priority_cache(key, cb) { |
|
|
|
var i = 0; |
|
|
|
async.forEachSeries(caches, function (cache, async_cb) { |
|
|
@ -41,21 +43,38 @@ var multi_caching = function (caches) { |
|
|
|
*/ |
|
|
|
self.wrap = function (key, work, cb) { |
|
|
|
get_from_highest_priority_cache(key, function (err, result, index) { |
|
|
|
if (err) { return cb(err); } |
|
|
|
if (result) { |
|
|
|
if (err) { |
|
|
|
return cb(err); |
|
|
|
} else if (result) { |
|
|
|
var caches_to_update = caches.slice(0, index); |
|
|
|
set_in_multiple_caches(caches_to_update, key, result, function (err) { |
|
|
|
cb(err, result); |
|
|
|
}); |
|
|
|
} else if (self.queues[key]) { |
|
|
|
self.queues[key].push(cb); |
|
|
|
} else { |
|
|
|
self.queues[key] = [cb]; |
|
|
|
work(function () { |
|
|
|
var work_args = Array.prototype.slice.call(arguments, 0); |
|
|
|
if (work_args[0]) { // assume first arg is an error
|
|
|
|
return cb(work_args[0]); |
|
|
|
self.queues[key].forEach(function (done) { |
|
|
|
done.call(null, work_args[0]); |
|
|
|
}); |
|
|
|
delete self.queues[key]; |
|
|
|
return; |
|
|
|
} |
|
|
|
set_in_multiple_caches(caches, key, work_args[1], function (err) { |
|
|
|
if (err) { return cb(err); } |
|
|
|
cb.apply(null, work_args); |
|
|
|
if (err) { |
|
|
|
self.queues[key].forEach(function (done) { |
|
|
|
done.call(null, err); |
|
|
|
}); |
|
|
|
delete self.queues[key]; |
|
|
|
return; |
|
|
|
} |
|
|
|
self.queues[key].forEach(function (done) { |
|
|
|
done.apply(null, work_args); |
|
|
|
}); |
|
|
|
delete self.queues[key]; |
|
|
|
}); |
|
|
|
}); |
|
|
|
} |
|
|
|