@@ -12,6 +12,16 @@ export type IRateLimit = {
12
12
expireAt ?: Date ;
13
13
} ;
14
14
15
+ export enum RateLimitTimes {
16
+ None = 0 ,
17
+ Second = 1000 ,
18
+ Minute = RateLimitTimes . Second * 60 ,
19
+ Hour = RateLimitTimes . Minute * 60 ,
20
+ Day = RateLimitTimes . Hour * 24 ,
21
+ Month = RateLimitTimes . Day * 30 ,
22
+ Year = RateLimitTimes . Day * 365
23
+ }
24
+
15
25
export class RateLimitModel extends BaseModel < IRateLimit > {
16
26
constructor ( storage ?: StorageService ) {
17
27
super ( 'ratelimits' , storage ) ;
@@ -26,25 +36,25 @@ export class RateLimitModel extends BaseModel<IRateLimit> {
26
36
incrementAndCheck ( identifier : string , method : string ) {
27
37
return Promise . all ( [
28
38
this . collection . findOneAndUpdate (
29
- { identifier, method, period : 'second' , time : { $gt : new Date ( Date . now ( ) - 1000 ) } } ,
39
+ { identifier, method, period : 'second' , time : { $gte : new Date ( Date . now ( ) - RateLimitTimes . Second ) } } ,
30
40
{
31
- $setOnInsert : { time : new Date ( ) , expireAt : new Date ( Date . now ( ) + 10 * 1000 ) } ,
41
+ $setOnInsert : { time : new Date ( ) , expireAt : new Date ( Date . now ( ) + 2 * RateLimitTimes . Second ) } ,
32
42
$inc : { count : 1 }
33
43
} ,
34
44
{ upsert : true , returnOriginal : false }
35
45
) ,
36
46
this . collection . findOneAndUpdate (
37
- { identifier, method, period : 'minute' , time : { $gt : new Date ( Date . now ( ) - 60 * 1000 ) } } ,
47
+ { identifier, method, period : 'minute' , time : { $gte : new Date ( Date . now ( ) - RateLimitTimes . Minute ) } } ,
38
48
{
39
- $setOnInsert : { time : new Date ( ) , expireAt : new Date ( Date . now ( ) + 2 * 60 * 1000 ) } ,
49
+ $setOnInsert : { time : new Date ( ) , expireAt : new Date ( Date . now ( ) + 2 * RateLimitTimes . Minute ) } ,
40
50
$inc : { count : 1 }
41
51
} ,
42
52
{ upsert : true , returnOriginal : false }
43
53
) ,
44
54
this . collection . findOneAndUpdate (
45
- { identifier, method, period : 'hour' , time : { $gt : new Date ( Date . now ( ) - 60 * 60 * 1000 ) } } ,
55
+ { identifier, method, period : 'hour' , time : { $gte : new Date ( Date . now ( ) - RateLimitTimes . Hour ) } } ,
46
56
{
47
- $setOnInsert : { time : new Date ( ) , expireAt : new Date ( Date . now ( ) + 62 * 60 * 1000 ) } ,
57
+ $setOnInsert : { time : new Date ( ) , expireAt : new Date ( Date . now ( ) + 2 * RateLimitTimes . Hour ) } ,
48
58
$inc : { count : 1 }
49
59
} ,
50
60
{ upsert : true , returnOriginal : false }
0 commit comments