| 1 | import { Injectable, OnModuleDestroy } from '@nestjs/common'; |
| 2 | import { ThrottlerStorage } from '@nestjs/throttler'; |
| 3 | import Redis from 'ioredis'; |
| 4 | |
| 5 | interface ThrottlerStorageRecord { |
| 6 | totalHits: number; |
| 7 | timeToExpire: number; |
| 8 | isBlocked: boolean; |
| 9 | timeToBlockExpire: number; |
| 10 | } |
| 11 | |
| 12 | @Injectable() |
| 13 | export class ThrottlerStorageRedis |
| 14 | implements ThrottlerStorage, OnModuleDestroy |
| 15 | { |
| 16 | private redis: Redis; |
| 17 | |
| 18 | constructor() { |
| 19 | this.redis = new Redis({ |
| 20 | host: process.env.REDIS_HOST || 'redis', |
| 21 | port: parseInt(process.env.REDIS_PORT || '6379'), |
| 22 | }); |
| 23 | } |
| 24 | |
| 25 | async increment( |
| 26 | key: string, |
| 27 | ttl: number, |
| 28 | limit: number, |
| 29 | blockDuration: number, |
| 30 | // throttlerName: string, |
| 31 | ): Promise<ThrottlerStorageRecord> { |
| 32 | const totalHits = await this.redis.incr(key); |
| 33 | |
| 34 | if (totalHits === 1) { |
| 35 | await this.redis.pexpire(key, ttl); |
| 36 | } |
| 37 | |
| 38 | const pttl = await this.redis.pttl(key); |
| 39 | const timeToExpire = pttl > 0 ? pttl : ttl; |
| 40 | const isBlocked = totalHits > limit; |
| 41 | const timeToBlockExpire = isBlocked ? blockDuration : 0; |
| 42 | |
| 43 | return { |
| 44 | totalHits, |
| 45 | timeToExpire, |
| 46 | isBlocked, |
| 47 | timeToBlockExpire, |
| 48 | }; |
| 49 | } |
| 50 | |
| 51 | async onModuleDestroy() { |
| 52 | await this.redis.quit(); |
| 53 | } |
| 54 | } |