/**
* 简单内存缓存
*/
interface CacheEntry<T> {
value: T;
expireAt: number;
}
export class SimpleCache<T> {
private cache = new Map<string, CacheEntry<T>>();
private ttl: number;
constructor(ttlSeconds: number = 3600) {
this.ttl = ttlSeconds * 1000;
}
set(key: string, value: T): void {
this.cache.set(key, {
value,
expireAt: Date.now() + this.ttl,
});
}
get(key: string): T | undefined {
const entry = this.cache.get(key);
if (!entry) return undefined;
if (Date.now() > entry.expireAt) {
this.cache.delete(key);
return undefined;
}
return entry.value;
}
has(key: string): boolean {
return this.get(key) !== undefined;
}
delete(key: string): void {
this.cache.delete(key);
}
clear(): void {
this.cache.clear();
}
// 清理过期条目
cleanup(): void {
const now = Date.now();
for (const [key, entry] of this.cache.entries()) {
if (now > entry.expireAt) {
this.cache.delete(key);
}
}
}
}