Skip to content

Instantly share code, notes, and snippets.

@alvarogfn
Created June 20, 2024 23:06
Show Gist options
  • Save alvarogfn/cf5533e65001d9850aa30f6b4973abaa to your computer and use it in GitHub Desktop.
Save alvarogfn/cf5533e65001d9850aa30f6b4973abaa to your computer and use it in GitHub Desktop.
caches a fetch call based on the parameters passed to fetch and a unique identifier.
const memoryCache = new Map<string, any>()
/**
* `resetCachedFetch` is a function that clears the cachedFetch cache.
* It does not take any parameters and does not return any value.
*/
export const resetCachedFetch = () => memoryCache.clear()
/**
* `cachedFetch` is a generic function that performs a fetch operation and caches the result.
* If the same fetch operation is performed again (i.e., the same key and parameters are used),
* the function will return the cached result instead of performing the fetch operation again.
*
* @param key - A unique identifier for the fetch operation.
* @param fetch - The fetch function to be performed.
* @param parameters - The parameters to be passed to the fetch function.
* @returns - The result of the fetch operation.
*/
export const cachedFetch = <T extends (...args: any) => Promise<any>>(
key: string,
fetch: T,
...parameters: Parameters<T>
): ReturnType<T> => {
const cacheKey = JSON.stringify({
uniqueKey: key,
...parameters
})
if (memoryCache.has(cacheKey)) return memoryCache.get(cacheKey)!
// eslint-disable-next-line no-useless-call
const response = fetch.call(null, ...parameters) as ReturnType<T>
memoryCache.set(cacheKey, response)
return response
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment