Files
lolympus-tournament-support/apps/api/src/modules/dakao/idempotency.cache.ts
T
2026-07-24 21:52:35 -07:00

36 lines
933 B
TypeScript

import { Injectable } from '@nestjs/common';
const TTL_MS = 5 * 60 * 1000;
const MAX_ENTRIES = 5000;
@Injectable()
export class IdempotencyCache {
private readonly entries = new Map<string, number>();
public has(key: string): boolean {
const expiresAt = this.entries.get(key);
if (expiresAt === undefined) return false;
if (expiresAt < Date.now()) {
this.entries.delete(key);
return false;
}
return true;
}
public remember(key: string): void {
this.evictExpired();
if (this.entries.size >= MAX_ENTRIES) {
const oldestKey: unknown = this.entries.keys().next().value;
if (typeof oldestKey === 'string') this.entries.delete(oldestKey);
}
this.entries.set(key, Date.now() + TTL_MS);
}
private evictExpired(): void {
const now = Date.now();
for (const [key, expiresAt] of this.entries) {
if (expiresAt < now) this.entries.delete(key);
}
}
}