Skip to content

Instantly share code, notes, and snippets.

@andyrichardson
Last active December 9, 2022 17:12
Show Gist options
  • Save andyrichardson/1f4c6ac20189185443c123a406b848e6 to your computer and use it in GitHub Desktop.
Save andyrichardson/1f4c6ac20189185443c123a406b848e6 to your computer and use it in GitHub Desktop.
A ttl cache for use with Dataloader's cacheMap option
export const ttlCache = <K extends string, V = any>({ ttl, maxSize }: { ttl: number, maxSize?: number }) => {
let cache: Record<K, { value: V; expiresAt: number } | undefined> = Object.create(null);
return {
set: (key: K, value: V) => {
const keys = Object.keys(cache) as K[];
if (maxSize && keys.length === maxSize) {
delete cache[keys[0]];
}
cache[key] = { value, expiresAt: Date.now() + ttl })
},
get: (key: K) => {
const entry = cache[key];
if (!entry) {
return undefined;
}
if (entry.expiresAt < Date.now()) {
delete cache[key];
return undefined;
}
return entry.value;
},
clear: () => (cache = Object.create(null)),
delete: (key: K) => (cache[key] = undefined),
};
};
@andyrichardson
Copy link
Author

@madiganz feel free to copy/change/redistribute as you please

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment