fix: add wrapper function for caching

This commit is contained in:
Christel Westerberg
2024-11-25 13:47:25 +01:00
parent 503b0bf186
commit 8bfc4065ed
7 changed files with 55 additions and 53 deletions

22
utils/cache.ts Normal file
View File

@@ -0,0 +1,22 @@
import stringify from "json-stable-stringify-without-jsonify"
import { cache as reactCache } from "react"
/**
* Wrapper function to handle caching of memoized requests that recieve objects as args.
* React Cache will use shallow equality of the arguments to determine if there is a cache hit,
* therefore we need to stringify the arguments to ensure that the cache works as expected.
* This function will handle the stingification of the arguments, the caching of the function,
* and the parsing of the arguments back to their original form.
*
* @param fn - The function to memoize
*/
export function cache<T extends (...args: any[]) => any>(fn: T) {
const cachedFunction = reactCache((stringifiedParams: string) => {
return fn(...JSON.parse(stringifiedParams))
})
return (...args: Parameters<T>): ReturnType<T> => {
const stringifiedParams = stringify(args)
return cachedFunction(stringifiedParams)
}
}