Skip to content

Commit 3e89fe4

Browse files
authored
Update README.md
1 parent 0e4a05e commit 3e89fe4

File tree

1 file changed

+69
-1
lines changed

1 file changed

+69
-1
lines changed

README.md

+69-1
Original file line numberDiff line numberDiff line change
@@ -7,4 +7,72 @@
77

88
## RediBox Throttle
99

10-
For now this only provides `throttle` and `pThrottle` lua scripts.
10+
Provides `throttle` and `pThrottle` lua scripts for [RediBox](https://github.com/redibox/core) redis clients.
11+
12+
### Installation
13+
---
14+
```bash
15+
npm i redibox-hook-throttle --save
16+
```
17+
18+
No configuration required.
19+
20+
### API
21+
---
22+
23+
### client.throttle(key, limit, seconds)
24+
25+
**Args**:
26+
- **key** - key name - ip, user id or some unique key to throttle X by
27+
- **limit** - limit amount, e.g. '20' requests
28+
- **seconds** - ttl in secondsof this limit, i.e, '60' - 20 requests per 60 seconds.
29+
30+
**Returns**:
31+
- ARRAY
32+
- **[0] throttled**: -> 1 if you should throttle/reject this request, 0 if still within limit
33+
- **[1] remaining**: -> how many times left until throttled, i.e. 11 requests left
34+
- **[2] ttl**: -> seconds remaining until limit resets
35+
36+
37+
**Example**:
38+
39+
In this example we have an express api server and we want to limit each user to no more than 10 requests per minute. We can use throttle in a middleware to achieve this.
40+
41+
```javascript
42+
const app = express();
43+
44+
app.use((req, res, next) => {
45+
RediBox.client
46+
.throttle(
47+
// key based on user id for uniqueness or some other identifier
48+
`throttle:${req.param('userId')}`,
49+
// 10 requests
50+
10,
51+
// per 60 seconds
52+
60
53+
).then((result) => {
54+
const throttled = result[0];
55+
const remainingRequests = result[1];
56+
const expiresInSeconds = result[2];
57+
58+
if (throttled) {
59+
return res.status(429).json({
60+
msg: `You have made too many requests recently, please try again in ${expiresInSeconds} seconds.`,
61+
});
62+
}
63+
64+
// if we want it later on in the request
65+
req.throttle = {
66+
remainingRequests,
67+
expiresInSeconds
68+
};
69+
70+
// we're all good here so allow user to continue
71+
next();
72+
}).catch(next);
73+
});
74+
```
75+
76+
### client.pthrottle(key, limit, milliseconds)
77+
78+
`pThrottle` is exactly the same as `throttle` but uses millisecond precision instead of seconds.

0 commit comments

Comments
 (0)