Skip to content

Commit 26820c4

Browse files
committed
feat(RateLimiter): add remaining() method to check requests left for an IP
1 parent 0ea7f74 commit 26820c4

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)