cache-in-memory.esm.js 1.2 KB

123456789101112131415161718192021222324252627282930313233
  1. function createInMemoryCache(options = { serializable: true }) {
  2. // eslint-disable-next-line functional/no-let
  3. let cache = {};
  4. return {
  5. get(key, defaultValue, events = {
  6. miss: () => Promise.resolve(),
  7. }) {
  8. const keyAsString = JSON.stringify(key);
  9. if (keyAsString in cache) {
  10. return Promise.resolve(options.serializable ? JSON.parse(cache[keyAsString]) : cache[keyAsString]);
  11. }
  12. const promise = defaultValue();
  13. const miss = (events && events.miss) || (() => Promise.resolve());
  14. return promise.then((value) => miss(value)).then(() => promise);
  15. },
  16. set(key, value) {
  17. // eslint-disable-next-line functional/immutable-data
  18. cache[JSON.stringify(key)] = options.serializable ? JSON.stringify(value) : value;
  19. return Promise.resolve(value);
  20. },
  21. delete(key) {
  22. // eslint-disable-next-line functional/immutable-data
  23. delete cache[JSON.stringify(key)];
  24. return Promise.resolve();
  25. },
  26. clear() {
  27. cache = {};
  28. return Promise.resolve();
  29. },
  30. };
  31. }
  32. export { createInMemoryCache };