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),
};
};
@AlexGodard
Copy link

Thank you!

@madiganz
Copy link

madiganz commented Dec 8, 2022

Hi Andy, I don't see a license on this and would like to use this code if it is open source. Any chance you could let me know the license for this?

@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