added first cache

This commit is contained in:
Bojan Kucera 2025-06-05 07:39:54 -04:00
parent eee6135867
commit 3fc123eca3
9 changed files with 210 additions and 9 deletions

View file

@ -0,0 +1,48 @@
import { CacheProvider } from '../types';
/**
* Simple in-memory cache provider.
*/
export class MemoryCache implements CacheProvider {
private store = new Map<string, any>();
private defaultTTL: number;
private keyPrefix: string;
constructor(options: { ttl?: number; keyPrefix?: string } = {}) {
this.defaultTTL = options.ttl ?? 3600;
this.keyPrefix = options.keyPrefix ?? 'cache:';
}
private getKey(key: string): string {
return `${this.keyPrefix}${key}`;
}
async get<T>(key: string): Promise<T | null> {
const fullKey = this.getKey(key);
const entry = this.store.get(fullKey);
if (!entry) return null;
if (entry.expiry < Date.now()) {
this.store.delete(fullKey);
return null;
}
return entry.value;
}
async set<T>(key: string, value: T, ttl?: number): Promise<void> {
const fullKey = this.getKey(key);
const expiry = Date.now() + 1000 * (ttl ?? this.defaultTTL);
this.store.set(fullKey, { value, expiry });
}
async del(key: string): Promise<void> {
this.store.delete(this.getKey(key));
}
async exists(key: string): Promise<boolean> {
return (await this.get(key)) !== null;
}
async clear(): Promise<void> {
this.store.clear();
}
}