27 lines
720 B
TypeScript
27 lines
720 B
TypeScript
import type { CacheService } from "./cache-service";
|
|
|
|
export class MemoryCacheService implements CacheService {
|
|
private cache = new Map<string, { value: any; expiry: number | null }>();
|
|
|
|
async get<T>(key: string): Promise<T | null> {
|
|
const item = this.cache.get(key);
|
|
if (!item) return null;
|
|
|
|
if (item.expiry && item.expiry < Date.now()) {
|
|
this.cache.delete(key);
|
|
return null;
|
|
}
|
|
|
|
return item.value as T;
|
|
}
|
|
|
|
async set<T>(key: string, value: T, ttlSeconds?: number): Promise<void> {
|
|
const expiry = ttlSeconds ? Date.now() + ttlSeconds * 1000 : null;
|
|
this.cache.set(key, { value, expiry });
|
|
}
|
|
|
|
async delete(key: string): Promise<void> {
|
|
this.cache.delete(key);
|
|
}
|
|
}
|