-
Notifications
You must be signed in to change notification settings - Fork 1
/
rateLimiter.js
40 lines (30 loc) · 1014 Bytes
/
rateLimiter.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
const uidRequestCount = {};
const uidLastRequestTime = {};
const uidLimitExpiryTime = {};
const customRateLimiter = (req, res, next) => {
const { uid } = req.body;
if (!uid) {
return res.status(400).json({ error: 'UID is required.' });
}
const currentTime = Date.now();
if (uidLimitExpiryTime[uid] && uidLimitExpiryTime[uid] > currentTime) {
return res.status(429).json({ error: '请求速率过高,请稍后重试' });
}
if (!uidRequestCount[uid]) {
uidRequestCount[uid] = 0;
uidLastRequestTime[uid] = currentTime;
}
const timeSinceLastRequest = currentTime - uidLastRequestTime[uid];
if (timeSinceLastRequest < 1000) {
uidRequestCount[uid] += 1;
} else {
uidRequestCount[uid] = 1;
uidLastRequestTime[uid] = currentTime;
}
if (uidRequestCount[uid] > 2) {
uidLimitExpiryTime[uid] = currentTime + 30000;
return res.status(429).json({ error: '请求速率过高,请稍后重试' });
}
next();
};
module.exports = { customRateLimiter };