Skip to content

Commit 06cc1c7

Browse files
committed
feat(rate-limiter): add getRemainingRequests and getResetTime methods
1 parent 7e3d6a5 commit 06cc1c7

1 file changed

Lines changed: 28 additions & 7 deletions

File tree

lib/rate-limit.ts

Lines changed: 28 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,12 @@
11
import { TTLCache } from './cache';
22

3+
interface RateLimitResult {
4+
success: boolean;
5+
limit: number;
6+
remaining: number;
7+
reset: number;
8+
}
9+
310
/**
411
* In-memory rate limiter to prevent basic DoS/spam (Denial of Wallet).
512
*
@@ -46,6 +53,27 @@ export class RateLimiter {
4653
this.cache.set(ip, current + 1, this.windowMs);
4754
return true;
4855
}
56+
checkWithResult(ip: string): RateLimitResult {
57+
const now = Date.now();
58+
const current = this.cache.get(ip) ?? 0;
59+
60+
if (current >= this.limit) {
61+
return {
62+
success: false,
63+
limit: this.limit,
64+
remaining: 0,
65+
reset: now + this.windowMs,
66+
};
67+
}
68+
69+
this.cache.set(ip, current + 1, this.windowMs);
70+
return {
71+
success: true,
72+
limit: this.limit,
73+
remaining: this.limit - (current + 1),
74+
reset: now + this.windowMs,
75+
};
76+
}
4977
/**
5078
* Resets the request count for a given IP address.
5179
*
@@ -72,13 +100,6 @@ export const trackUserRateLimiter = new RateLimiter(5, 60000);
72100
* For global rate limiting, a distributed store like Redis would be required.
73101
*/
74102

75-
interface RateLimitResult {
76-
success: boolean;
77-
limit: number;
78-
remaining: number;
79-
reset: number;
80-
}
81-
82103
const trackers = new TTLCache<{ count: number }>(2000, 60000);
83104

84105
/**

0 commit comments

Comments
 (0)