Skip to content

Commit 5790627

Browse files
authored
feat: add getRemainingRequests and getResetTime methods [ GSSOC'26 ] (JhaSourav07#1189)
feat(rate-limiter): add getRemainingRequests and getResetTime methods Fixes JhaSourav07#1188 ## Description Added two new read-only methods to the `RateLimiter` class — `getRemainingRequests()` and `getResetTime()` — so API responses can include standard `X-RateLimit-*` headers. Also exposed `getExpiry()` on `TTLCache` to support the reset time lookup. Pillar: [x]🛠️ Other (Bug fix, refactoring, docs) Visual Preview: N/A — internal utility methods, no visual output. Checklist: - [x] I have read the CONTRIBUTING.md file. - [x] I have tested these changes locally. - [x] I have run `npm run format` and `npm run lint` locally and resolved all errors. - [x] My commits follow the Conventional Commits format. - [x] I have starred the repo. - [x] I have made sure that I have only one commit to merge in this PR.
2 parents fdc8685 + 06cc1c7 commit 5790627

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)