29 lines
804 B
TypeScript
29 lines
804 B
TypeScript
const DEFAULT_MIN_INTERVAL_MS = 8000;
|
|
const JITTER_MAX_MS = 8000;
|
|
|
|
export class WhatsAppThrottleClass {
|
|
private lastSentAt: Map<string, number> = new Map();
|
|
private minIntervalMs: number;
|
|
|
|
constructor(minIntervalMs: number = DEFAULT_MIN_INTERVAL_MS) {
|
|
this.minIntervalMs = minIntervalMs;
|
|
}
|
|
|
|
canSend(companyId: string): boolean {
|
|
const lastSent = this.lastSentAt.get(companyId);
|
|
if (!lastSent) {
|
|
return true;
|
|
}
|
|
|
|
const elapsed = Date.now() - lastSent;
|
|
const jitter = Math.floor(Math.random() * JITTER_MAX_MS);
|
|
const requiredInterval = this.minIntervalMs + jitter;
|
|
|
|
return elapsed >= requiredInterval;
|
|
}
|
|
|
|
recordSent(companyId: string): void {
|
|
this.lastSentAt.set(companyId, Date.now());
|
|
}
|
|
}
|