Windshaft-cartodb/lib/cache/surrogate-keys-cache.js

56 lines
1.5 KiB
JavaScript
Raw Normal View History

'use strict';
var queue = require('queue-async');
2015-01-23 23:37:38 +08:00
/**
* @param {Array|Object} cacheBackends each backend backend should respond to `invalidate(cacheObject, callback)` method
2015-01-23 23:37:38 +08:00
* @constructor
*/
function SurrogateKeysCache(cacheBackends) {
this.cacheBackends = Array.isArray(cacheBackends) ? cacheBackends : [cacheBackends];
2015-01-23 23:37:38 +08:00
}
module.exports = SurrogateKeysCache;
/**
* @param response should respond to `header(key, value)` method
* @param cacheObject should respond to `key() -> String` method
*/
SurrogateKeysCache.prototype.tag = function(response, cacheObject) {
var newKey = cacheObject.key();
2015-09-17 08:03:09 +08:00
response.set('Surrogate-Key', appendSurrogateKey(
response.get('Surrogate-Key'),
Array.isArray(newKey) ? cacheObject.key().join(' ') : newKey
));
2015-01-23 23:37:38 +08:00
};
function appendSurrogateKey(currentKey, newKey) {
if (!!currentKey) {
newKey = currentKey + ' ' + newKey;
}
return newKey;
}
2015-01-23 23:37:38 +08:00
/**
* @param cacheObject should respond to `key() -> String` method
* @param {Function} callback
*/
SurrogateKeysCache.prototype.invalidate = function(cacheObject, callback) {
var invalidationQueue = queue(this.cacheBackends.length);
this.cacheBackends.forEach(function(cacheBackend) {
invalidationQueue.defer(function(cacheBackend, done) {
cacheBackend.invalidate(cacheObject, done);
}, cacheBackend);
});
invalidationQueue.awaitAll(function(err, result) {
if (err) {
return callback(err);
}
callback(null, result);
});
2015-01-23 23:37:38 +08:00
};