Created
June 30, 2022 01:53
-
-
Save magiskboy/449df0b6418648e3faf4fa11bdbcdda2 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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