blob: 9cc25675d85c77d163b5e5f75b3ca71a83734b55 (
plain)
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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
|
import * as Limiter from 'ratelimiter';
import limiterDB from '../db/redis';
import { IEndpoint } from './endpoints';
import { IAuthContext } from './authenticate';
export default (endpoint: IEndpoint, ctx: IAuthContext) => new Promise((ok, reject) => {
const limitKey = endpoint.hasOwnProperty('limitKey')
? endpoint.limitKey
: endpoint.name;
const hasMinInterval =
endpoint.hasOwnProperty('minInterval');
const hasRateLimit =
endpoint.hasOwnProperty('limitDuration') &&
endpoint.hasOwnProperty('limitMax');
if (hasMinInterval) {
min();
} else if (hasRateLimit) {
max();
} else {
ok();
}
// Short-term limit
function min(): void {
const minIntervalLimiter = new Limiter({
id: `${ctx.user._id}:${limitKey}:min`,
duration: endpoint.minInterval,
max: 1,
db: limiterDB
});
minIntervalLimiter.get((limitErr, limit) => {
if (limitErr) {
reject('ERR');
} else if (limit.remaining === 0) {
reject('BRIEF_REQUEST_INTERVAL');
} else {
if (hasRateLimit) {
max();
} else {
ok();
}
}
});
}
// Long term limit
function max(): void {
const limiter = new Limiter({
id: `${ctx.user._id}:${limitKey}`,
duration: endpoint.limitDuration,
max: endpoint.limitMax,
db: limiterDB
});
limiter.get((limitErr, limit) => {
if (limitErr) {
reject('ERR');
} else if (limit.remaining === 0) {
reject('RATE_LIMIT_EXCEEDED');
} else {
ok();
}
});
}
});
|