|
| 1 | +import { BaseModel } from './base'; |
| 2 | +import { ObjectID } from 'mongodb'; |
| 3 | + |
| 4 | +export type IRateLimit = { |
| 5 | + _id?: ObjectID; |
| 6 | + identifier: string; |
| 7 | + method: string; |
| 8 | + period: string; |
| 9 | + count: number; |
| 10 | + time?: Date; |
| 11 | + expireAt?: Date; |
| 12 | + value?: any; |
| 13 | +}; |
| 14 | + |
| 15 | +export class RateLimit extends BaseModel<IRateLimit> { |
| 16 | + constructor() { |
| 17 | + super('ratelimits'); |
| 18 | + } |
| 19 | + allowedPaging = []; |
| 20 | + |
| 21 | + onConnect() { |
| 22 | + this.collection.createIndex({ identifier: 1, time: 1, method: 1, count: 1 }, { background: true }); |
| 23 | + this.collection.createIndex({ expireAt: 1 }, { expireAfterSeconds: 0, background: true }); |
| 24 | + } |
| 25 | + |
| 26 | + incrementAndCheck(identifier: string, method: string) { |
| 27 | + return Promise.all([ |
| 28 | + this.collection.findOneAndUpdate( |
| 29 | + { identifier, method, period: 'second', time: {$gt: new Date(Date.now() - 1000)} }, |
| 30 | + { |
| 31 | + $setOnInsert: { time: new Date(), expireAt: new Date(Date.now() + 10 * 1000) }, |
| 32 | + $inc: { count: 1 } |
| 33 | + }, |
| 34 | + { upsert: true, returnOriginal: false } |
| 35 | + ), |
| 36 | + this.collection.findOneAndUpdate( |
| 37 | + { identifier, method, period: 'minute', time: { $gt: new Date(Date.now() - 60 * 1000) } }, |
| 38 | + { |
| 39 | + $setOnInsert: { time: new Date(), expireAt: new Date(Date.now() + 2 * 60 * 1000) }, |
| 40 | + $inc: { count: 1 } |
| 41 | + }, |
| 42 | + { upsert: true, returnOriginal: false } |
| 43 | + ), |
| 44 | + this.collection.findOneAndUpdate( |
| 45 | + { identifier, method, period: 'hour', time: { $gt: new Date(Date.now() - 60 * 60 * 1000) } }, |
| 46 | + { |
| 47 | + $setOnInsert: { time: new Date(), expireAt: new Date(Date.now() + 2 * 60 * 1000) }, |
| 48 | + $inc: { count: 1 } |
| 49 | + }, |
| 50 | + { upsert: true, returnOriginal: false } |
| 51 | + ), |
| 52 | + ]); |
| 53 | + } |
| 54 | +} |
| 55 | + |
| 56 | +export let RateLimitModel = new RateLimit(); |
0 commit comments