Skip to content

Instantly share code, notes, and snippets.

@mainarthur
Last active February 9, 2024 21:04
Show Gist options
  • Save mainarthur/13aaf67c6a7a64756496074008e879f0 to your computer and use it in GitHub Desktop.
Save mainarthur/13aaf67c6a7a64756496074008e879f0 to your computer and use it in GitHub Desktop.
JS/TS Implementation of RAM caching with efficient expires
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