Skip to content

Instantly share code, notes, and snippets.

@Greenheart
Created May 18, 2024 08:49
Show Gist options
  • Save Greenheart/6bd50399938f1559082d04f67cf2f039 to your computer and use it in GitHub Desktop.
Save Greenheart/6bd50399938f1559082d04f67cf2f039 to your computer and use it in GitHub Desktop.
In memory caching to reduce data usage for frequent API requests, repeated data processing or similar use cases.
const FIVE_MINUTES = 1000 * 60 * 5
function createCache<K, V>({ maxAge }: { maxAge: number }) {
const cache = new Map<
K,
V & { cachedAt: ReturnType<(typeof Date)['now']> }
>()
return {
set(key: K, value: V) {
cache.set(key, { ...value, cachedAt: Date.now() })
},
/**
* Verify that the value both exists and that it's newer than `maxAge`
*/
has(key: K) {
const value = cache.get(key)
if (value && Date.now() - value.cachedAt < maxAge) {
return true
}
return false
},
get(key: K) {
const value = cache.get(key)
if (value) {
// Make a copy with the actual data and delete internal caching details
const dataOnly: V = { ...value }
delete (dataOnly as V & { cachedAt?: number }).cachedAt
return dataOnly
}
},
}
}
const cachedCases = createCache<Case['beteckning'], Case>({
maxAge: FIVE_MINUTES,
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment