Skip to content

Instantly share code, notes, and snippets.

@magiskboy
Created June 30, 2022 01:53
Show Gist options
  • Save magiskboy/449df0b6418648e3faf4fa11bdbcdda2 to your computer and use it in GitHub Desktop.
Save magiskboy/449df0b6418648e3faf4fa11bdbcdda2 to your computer and use it in GitHub Desktop.
const lib = require("./lib");
/**
* @param {number} id
* @param {(number) => Promise<import('./lib').CacheValue>} fetcher
* @typedef {Object} Product
* @property {number} id
* @returns {Promise<Product>|undefined}
*/
async function getProductWithCached(id, fetcher) {
const cachedKey = id.toString();
const cached = lib.cache.get(cachedKey);
if (!cached) {
const pPromise = fetcher(id).catch(() => Promise.resolve());
lib.cache.set(cachedKey, pPromise);
return pPromise;
}
if (cached.isValid) {
return cached.value;
}
const pPromise = fetcher(id).catch(() => Promise.resolve(cached.value));
lib.cache.set(cachedKey, pPromise);
return pPromise;
}
module.exports = {
getProductWithCached,
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment