Skip to content

Commit cb47e46

Browse files
authored
feat: add remaining() method to check requests left for an IP (JhaSourav07#1638)
## Description Adds a `remaining(ip)` method to `RateLimiter` that returns how many requests an IP has left in the current window without consuming one. Useful for setting `X-RateLimit-Remaining` response headers without side effects. Fixes JhaSourav07#1634 ## Pillar - [x] 🛠️ Other (Bug fix, refactoring, docs) ## Visual Preview N/A — internal rate limiting logic, no visual output. ## Checklist before requesting a review: - [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 updated `README.md` if I added a new theme or URL parameter. - [x] I have starred the repo. - [x] I have made sure that I have only one commit to merge in this PR. - [ ] The SVG output matches the CommitPulse "premium quality" aesthetic standard. - [ ] (Recommended) I joined the CommitPulse Discord community.
2 parents 2534797 + 13db540 commit cb47e46

1 file changed

Lines changed: 18 additions & 0 deletions

File tree

lib/rate-limit.ts

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -107,6 +107,24 @@ export class RateLimiter {
107107
async reset(ip: string): Promise<void> {
108108
await this.cache.delete(ip);
109109
}
110+
/**
111+
* Returns the number of remaining requests allowed for a given IP
112+
* in the current window.
113+
*
114+
* Does not consume a request — use `check()` for that.
115+
*
116+
* @param ip - The IP address to check.
117+
* @returns Promise resolving to the number of remaining requests,
118+
* or the full limit if the IP has no recorded requests.
119+
*
120+
* @example
121+
* const left = await rateLimiter.remaining("192.168.1.1");
122+
* console.log(`You have ${left} requests left.`);
123+
*/
124+
async remaining(ip: string): Promise<number> {
125+
const current = (await this.cache.get(ip)) ?? 0;
126+
return Math.max(0, this.limit - current);
127+
}
110128

111129
allow(ip: string): void {
112130
this.allowlist.add(ip);

0 commit comments

Comments
 (0)