@@ -12,6 +12,16 @@ export type IRateLimit = {
1212 expireAt ?: Date ;
1313} ;
1414
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+
1525export class RateLimitModel extends BaseModel < IRateLimit > {
1626 constructor ( storage ?: StorageService ) {
1727 super ( 'ratelimits' , storage ) ;
@@ -26,25 +36,25 @@ export class RateLimitModel extends BaseModel<IRateLimit> {
2636 incrementAndCheck ( identifier : string , method : string ) {
2737 return Promise . all ( [
2838 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 ) } } ,
3040 {
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 ) } ,
3242 $inc : { count : 1 }
3343 } ,
3444 { upsert : true , returnOriginal : false }
3545 ) ,
3646 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 ) } } ,
3848 {
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 ) } ,
4050 $inc : { count : 1 }
4151 } ,
4252 { upsert : true , returnOriginal : false }
4353 ) ,
4454 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 ) } } ,
4656 {
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 ) } ,
4858 $inc : { count : 1 }
4959 } ,
5060 { upsert : true , returnOriginal : false }
0 commit comments