2018-10-23 23:45:42 +08:00
|
|
|
'use strict';
|
|
|
|
|
2015-04-27 22:22:37 +08:00
|
|
|
var queue = require('queue-async');
|
|
|
|
|
2015-01-23 23:37:38 +08:00
|
|
|
/**
|
2015-04-27 22:22:37 +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
|
|
|
|
*/
|
2019-10-22 01:07:24 +08:00
|
|
|
function SurrogateKeysCache (cacheBackends) {
|
2015-04-27 22:22:37 +08:00
|
|
|
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
|
|
|
|
*/
|
2019-10-22 01:07:24 +08:00
|
|
|
SurrogateKeysCache.prototype.tag = function (response, cacheObject) {
|
2015-07-13 22:15:34 +08:00
|
|
|
var newKey = cacheObject.key();
|
2015-09-17 08:03:09 +08:00
|
|
|
response.set('Surrogate-Key', appendSurrogateKey(
|
|
|
|
response.get('Surrogate-Key'),
|
2015-07-13 22:15:34 +08:00
|
|
|
Array.isArray(newKey) ? cacheObject.key().join(' ') : newKey
|
|
|
|
));
|
2015-01-23 23:37:38 +08:00
|
|
|
};
|
|
|
|
|
2019-10-22 01:07:24 +08:00
|
|
|
function appendSurrogateKey (currentKey, newKey) {
|
|
|
|
if (currentKey) {
|
2015-07-13 22:15:34 +08:00
|
|
|
newKey = currentKey + ' ' + newKey;
|
|
|
|
}
|
|
|
|
return newKey;
|
|
|
|
}
|
|
|
|
|
2015-01-23 23:37:38 +08:00
|
|
|
/**
|
|
|
|
* @param cacheObject should respond to `key() -> String` method
|
|
|
|
* @param {Function} callback
|
|
|
|
*/
|
2019-10-22 01:07:24 +08:00
|
|
|
SurrogateKeysCache.prototype.invalidate = function (cacheObject, callback) {
|
2015-04-27 22:22:37 +08:00
|
|
|
var invalidationQueue = queue(this.cacheBackends.length);
|
|
|
|
|
2019-10-22 01:07:24 +08:00
|
|
|
this.cacheBackends.forEach(function (cacheBackend) {
|
|
|
|
invalidationQueue.defer(function (cacheBackend, done) {
|
2015-04-27 22:22:37 +08:00
|
|
|
cacheBackend.invalidate(cacheObject, done);
|
|
|
|
}, cacheBackend);
|
|
|
|
});
|
|
|
|
|
2019-10-22 01:07:24 +08:00
|
|
|
invalidationQueue.awaitAll(function (err, result) {
|
2015-04-27 22:22:37 +08:00
|
|
|
if (err) {
|
|
|
|
return callback(err);
|
|
|
|
}
|
|
|
|
callback(null, result);
|
|
|
|
});
|
2015-01-23 23:37:38 +08:00
|
|
|
};
|