2017-05-03 15:35:00 +02:00
|
|
|
/*
|
|
|
|
MIT License http://www.opensource.org/licenses/mit-license.php
|
|
|
|
Author Tobias Koppers @sokra
|
|
|
|
*/
|
|
|
|
var createInnerCallback = require("./createInnerCallback");
|
|
|
|
|
2017-08-14 05:01:11 +02:00
|
|
|
function UnsafeCachePlugin(source, filterPredicate, cache, withContext, target) {
|
2017-05-03 15:35:00 +02:00
|
|
|
this.source = source;
|
|
|
|
this.filterPredicate = filterPredicate;
|
2017-08-14 05:01:11 +02:00
|
|
|
this.withContext = withContext;
|
2017-05-03 15:35:00 +02:00
|
|
|
this.cache = cache || {};
|
|
|
|
this.target = target;
|
|
|
|
}
|
|
|
|
module.exports = UnsafeCachePlugin;
|
|
|
|
|
2017-08-14 05:01:11 +02:00
|
|
|
function getCacheId(request, withContext) {
|
2017-05-03 15:35:00 +02:00
|
|
|
return JSON.stringify({
|
2017-08-14 05:01:11 +02:00
|
|
|
context: withContext ? request.context : "",
|
2017-05-03 15:35:00 +02:00
|
|
|
path: request.path,
|
|
|
|
query: request.query,
|
|
|
|
request: request.request
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
UnsafeCachePlugin.prototype.apply = function(resolver) {
|
|
|
|
var filterPredicate = this.filterPredicate;
|
|
|
|
var cache = this.cache;
|
|
|
|
var target = this.target;
|
2017-08-14 05:01:11 +02:00
|
|
|
var withContext = this.withContext;
|
2017-05-03 15:35:00 +02:00
|
|
|
resolver.plugin(this.source, function(request, callback) {
|
|
|
|
if(!filterPredicate(request)) return callback();
|
2017-08-14 05:01:11 +02:00
|
|
|
var cacheId = getCacheId(request, withContext);
|
2017-05-03 15:35:00 +02:00
|
|
|
var cacheEntry = cache[cacheId];
|
|
|
|
if(cacheEntry) {
|
|
|
|
return callback(null, cacheEntry);
|
|
|
|
}
|
|
|
|
resolver.doResolve(target, request, null, createInnerCallback(function(err, result) {
|
|
|
|
if(err) return callback(err);
|
|
|
|
if(result) return callback(null, cache[cacheId] = result);
|
|
|
|
callback();
|
|
|
|
}, callback));
|
|
|
|
});
|
|
|
|
};
|