Last active
December 9, 2022 17:12
-
-
Save andyrichardson/1f4c6ac20189185443c123a406b848e6 to your computer and use it in GitHub Desktop.
A ttl cache for use with Dataloader's cacheMap option
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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), | |
}; | |
}; |
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?
@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
Thank you!