forked from bitpay/bitcore
/
rateLimit.ts
56 lines (51 loc) · 1.71 KB
/
rateLimit.ts
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
import { BaseModel } from './base';
import { ObjectID } from 'mongodb';
export type IRateLimit = {
_id?: ObjectID;
identifier: string;
method: string;
period: string;
count: number;
time?: Date;
expireAt?: Date;
value?: any;
};
export class RateLimit extends BaseModel<IRateLimit> {
constructor() {
super('ratelimits');
}
allowedPaging = [];
onConnect() {
this.collection.createIndex({ identifier: 1, time: 1, method: 1, count: 1 }, { background: true });
this.collection.createIndex({ expireAt: 1 }, { expireAfterSeconds: 0, background: true });
}
incrementAndCheck(identifier: string, method: string) {
return Promise.all([
this.collection.findOneAndUpdate(
{ identifier, method, period: 'second', time: {$gt: new Date(Date.now() - 1000)} },
{
$setOnInsert: { time: new Date(), expireAt: new Date(Date.now() + 10 * 1000) },
$inc: { count: 1 }
},
{ upsert: true, returnOriginal: false }
),
this.collection.findOneAndUpdate(
{ identifier, method, period: 'minute', time: { $gt: new Date(Date.now() - 60 * 1000) } },
{
$setOnInsert: { time: new Date(), expireAt: new Date(Date.now() + 2 * 60 * 1000) },
$inc: { count: 1 }
},
{ upsert: true, returnOriginal: false }
),
this.collection.findOneAndUpdate(
{ identifier, method, period: 'hour', time: { $gt: new Date(Date.now() - 60 * 60 * 1000) } },
{
$setOnInsert: { time: new Date(), expireAt: new Date(Date.now() + 2 * 60 * 1000) },
$inc: { count: 1 }
},
{ upsert: true, returnOriginal: false }
),
]);
}
}
export let RateLimitModel = new RateLimit();