Skip to content

Instantly share code, notes, and snippets.

@composite
Last active March 16, 2024 10:04
Show Gist options
  • Save composite/c1c551c18de9a69bfe0a8f430a84e5a5 to your computer and use it in GitHub Desktop.
Save composite/c1c551c18de9a69bfe0a8f430a84e5a5 to your computer and use it in GitHub Desktop.
React weak argument using JSON based cache function for Server Component: useful to assign argument as object, array or any serializable values.
import hash from 'object-hash';
export type ObjectCacheFunction<A extends unknown[], V> = (...args: A) => V;
const objectMap = cache(() => new Map<string, any[]>());
export const objectCache = <A extends unknown[], V>(fn: ObjectCacheFunction<A, V>): ObjectCacheFunction<A, V> => {
const map = objectMap();
return new Proxy(
cache((s: string) => fn(...(map.get(s) as A))),
{
apply(target, _, args) {
const key = hash(args);
map.set(key, args);
return target(key);
},
}
) as unknown as ObjectCacheFunction<A, V>;
};
export type WeakCacheFunction<A extends unknown[], V> = (...args: A) => V;
export const weakCache = <A extends unknown[], V>(fn: WeakCacheFunction<A, V>): WeakCacheFunction<A, V> => {
return new Proxy(
cache((s: string) => fn(...JSON.parse(s))),
{
apply(target, _, args) {
// use serializable verification for safety argument cache!
//if (!isSerializable(args))
// throw new TypeError('weakCache error: arguments must be serializable for check arguments equality.');
return target(JSON.stringify(args));
},
}
) as unknown as WeakCacheFunction<A, V>;
};
// How to use: just same as react cache! and use it in Server Component.
const weakCachedFn = weakCache((a: string, b:number, c: { foo: string }, d: number[]) => {
console.log("I'll show you when all serializable argument value based cache hit!", a, b, c, d);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment