Last active
February 9, 2024 21:04
-
-
Save mainarthur/13aaf67c6a7a64756496074008e879f0 to your computer and use it in GitHub Desktop.
JS/TS Implementation of RAM caching with efficient expires
This file contains hidden or 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 type CacheStorage = { | |
set: (key: string, value: string) => Promise<boolean>; | |
get: (key: string) => Promise<string | null>; | |
}; | |
type CacheValue = { value: string; expireTime: number } | |
export const getRamCacheClient = () => { | |
const cache: Record<string, CacheValue> = {}; | |
return { | |
async set(key, value) { | |
cache[key] = { | |
value, | |
expireTime: Date.now() + DEFAULT_EXPIRE_TIME * 1000, | |
}; | |
return true; | |
}, | |
async get(key) { | |
const isCached = !!cache[key]; | |
if (!isCached) return null; | |
const isExpired = cache[key].expireTime < Date.now(); | |
if (isExpired) return null; | |
return cache[key].value; | |
}, | |
} as CacheStorage; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment