UnsafeCachePlugin.js 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  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
  25. .getHook(this.source)
  26. .tapAsync("UnsafeCachePlugin", (request, resolveContext, callback) => {
  27. if (!this.filterPredicate(request)) return callback();
  28. const cacheId = getCacheId(request, this.withContext);
  29. const cacheEntry = this.cache[cacheId];
  30. if (cacheEntry) {
  31. return callback(null, cacheEntry);
  32. }
  33. resolver.doResolve(
  34. target,
  35. request,
  36. null,
  37. resolveContext,
  38. (err, result) => {
  39. if (err) return callback(err);
  40. if (result) return callback(null, (this.cache[cacheId] = result));
  41. callback();
  42. }
  43. );
  44. });
  45. }
  46. };