33 lines
913 B
TypeScript
33 lines
913 B
TypeScript
import { Injectable } from '@nestjs/common';
|
|
|
|
const WINDOW_MS = 60_000;
|
|
const MAX_PER_WINDOW = 10;
|
|
|
|
@Injectable()
|
|
export class RegistrationRateLimitService {
|
|
private hits: Map<string, number[]> = new Map();
|
|
|
|
isAllowed(ip: string, now: number = Date.now()): boolean {
|
|
const arr = (this.hits.get(ip) ?? []).filter((t) => now - t < WINDOW_MS);
|
|
this.hits.set(ip, arr);
|
|
return arr.length < MAX_PER_WINDOW;
|
|
}
|
|
|
|
record(ip: string, now: number = Date.now()): void {
|
|
const arr = (this.hits.get(ip) ?? []).filter((t) => now - t < WINDOW_MS);
|
|
arr.push(now);
|
|
this.hits.set(ip, arr);
|
|
}
|
|
|
|
tryConsume(ip: string, now: number = Date.now()): boolean {
|
|
const arr = (this.hits.get(ip) ?? []).filter((t) => now - t < WINDOW_MS);
|
|
if (arr.length >= MAX_PER_WINDOW) {
|
|
this.hits.set(ip, arr);
|
|
return false;
|
|
}
|
|
arr.push(now);
|
|
this.hits.set(ip, arr);
|
|
return true;
|
|
}
|
|
}
|