30 lines
568 B
TypeScript
30 lines
568 B
TypeScript
type CacheEntry<T> = {
|
|
value: T;
|
|
expiresAt: number;
|
|
};
|
|
|
|
export class MemoryCache {
|
|
private readonly store = new Map<string, CacheEntry<unknown>>();
|
|
|
|
public get<T>(key: string): T | undefined {
|
|
const hit = this.store.get(key);
|
|
if (!hit) {
|
|
return undefined;
|
|
}
|
|
|
|
if (Date.now() >= hit.expiresAt) {
|
|
this.store.delete(key);
|
|
return undefined;
|
|
}
|
|
|
|
return hit.value as T;
|
|
}
|
|
|
|
public set<T>(key: string, value: T, ttlMs: number): void {
|
|
this.store.set(key, {
|
|
value,
|
|
expiresAt: Date.now() + ttlMs
|
|
});
|
|
}
|
|
}
|