Files
mb-grid-solutions.com/lib/services/cache/memory-cache-service.ts
2026-02-07 01:11:28 +01:00

31 lines
780 B
TypeScript

import type { CacheService, CacheSetOptions } from "./cache-service";
type Entry = {
value: unknown;
expiresAt?: number;
};
export class MemoryCacheService implements CacheService {
private readonly store = new Map<string, Entry>();
async get<T>(key: string) {
const entry = this.store.get(key);
if (!entry) return undefined;
if (entry.expiresAt && Date.now() > entry.expiresAt) {
this.store.delete(key);
return undefined;
}
return entry.value as T;
}
async set<T>(key: string, value: T, options?: CacheSetOptions) {
const ttl = options?.ttlSeconds;
const expiresAt = ttl ? Date.now() + ttl * 1000 : undefined;
this.store.set(key, { value, expiresAt });
}
async del(key: string) {
this.store.delete(key);
}
}