Skip to content

Commit 071386c

Browse files
committed
docs: better peek example
1 parent 4d527cd commit 071386c

File tree

1 file changed

+26
-1
lines changed

1 file changed

+26
-1
lines changed

README.md

Lines changed: 26 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@ $ npm install async-ratelimiter --save
1919

2020
## Usage
2121

22-
A simple middleware implementation for whatever HTTP server:
22+
The most straightforward way to use the rate limiter:
2323

2424
```js
2525
'use strict'
@@ -32,6 +32,29 @@ const rateLimiter = new RateLimiter({
3232
db: new Redis()
3333
})
3434

35+
const apiQuota = async (req, res, next) => {
36+
const clientIp = getClientIp(req)
37+
const limit = await rateLimiter.get({ id: clientIp })
38+
39+
if (!res.writableEnded) {
40+
res.setHeader('X-Rate-Limit-Limit', limit.total)
41+
res.setHeader('X-Rate-Limit-Remaining', Math.max(0, limit.remaining - 1))
42+
res.setHeader('X-Rate-Limit-Reset', limit.reset)
43+
}
44+
45+
return !limit.remaining
46+
? sendFail({
47+
req,
48+
res,
49+
code: HTTPStatus.TOO_MANY_REQUESTS,
50+
message: MESSAGES.RATE_LIMIT_EXCEDEED()
51+
})
52+
: next(req, res)
53+
}
54+
```
55+
For scenarios where you want to check the limit status before consuming a request, you should to pass `{ peek: true }`:
56+
57+
```js
3558
const apiQuota = async (req, res, next) => {
3659
const clientIp = getClientIp(req)
3760

@@ -60,6 +83,8 @@ const apiQuota = async (req, res, next) => {
6083
}
6184
```
6285

86+
87+
6388
## API
6489

6590
### constructor(options)

0 commit comments

Comments
 (0)