You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

UnsafeCachePlugin.js 1.2KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. Author Tobias Koppers @sokra
  4. */
  5. "use strict";
  6. function getCacheId(request, withContext) {
  7. return JSON.stringify({
  8. context: withContext ? request.context : "",
  9. path: request.path,
  10. query: request.query,
  11. request: request.request
  12. });
  13. }
  14. module.exports = class UnsafeCachePlugin {
  15. constructor(source, filterPredicate, cache, withContext, target) {
  16. this.source = source;
  17. this.filterPredicate = filterPredicate;
  18. this.withContext = withContext;
  19. this.cache = cache || {};
  20. this.target = target;
  21. }
  22. apply(resolver) {
  23. const target = resolver.ensureHook(this.target);
  24. resolver.getHook(this.source).tapAsync("UnsafeCachePlugin", (request, resolveContext, callback) => {
  25. if(!this.filterPredicate(request)) return callback();
  26. const cacheId = getCacheId(request, this.withContext);
  27. const cacheEntry = this.cache[cacheId];
  28. if(cacheEntry) {
  29. return callback(null, cacheEntry);
  30. }
  31. resolver.doResolve(target, request, null, resolveContext, (err, result) => {
  32. if(err) return callback(err);
  33. if(result) return callback(null, this.cache[cacheId] = result);
  34. callback();
  35. });
  36. });
  37. }
  38. };