DEV Community

Discussion on: Cache API in JavaScript - with just 20 lines of code.

Collapse
 
eyalshalev profile image
Eyal Shalev • Edited

Note: if you need caching for production projects, I highly recommend searching for existing implementations (or at least existing algorithms).

Otherwise I have some notes:

  1. The current implementation only accepts the URL. But usually the same URL is used with different parameters, http methods or headers. Because not all of the possible keys can be mapped, I recommend accepting a key, and a function (to be used if the key is missing).
  2. Some data will need to be cached for different amount of time, so accepting a parameter for it is a good idea. That would mean using a setInterval for each key, or replacing the cache[key].time with a validUntil time object.
  3. Because you are deleting the cache after a fixed point of time, there is no need to keep the cache centralized, and it will be easier to just implement a memoize function that deleted the cache after a certain amount of time.
function memoize(fn, delAfter = 1000000) {
  const missing = Symbol("missing");
  let cache = missing;
  return async () => {
    if (cache === missing) {
       cache = Promise.resolve(fn());
       setTimeout(() => cache = missing, delAfter);
    }
    return await cache;
  }
}
const foo = memoize(() => fetch("https://foo/bar", { method: " POST", body: JSON.stringify({bar:1}) }))

// Will only do a single fetch.
console.log(await foo(), await foo())

Enter fullscreen mode Exit fullscreen mode
Collapse
 
rajeshroyal profile image
Rajesh Royal

restep++