2026-05-22 23:09:16 +08:00
|
|
|
import { Injectable } from '@nestjs/common';
|
|
|
|
|
import { ThrottlerStorage } from '@nestjs/throttler';
|
|
|
|
|
import { RedisService } from '../../infrastructure/redis/redis.service';
|
|
|
|
|
|
|
|
|
|
@Injectable()
|
|
|
|
|
export class RedisThrottlerStorage implements ThrottlerStorage {
|
|
|
|
|
constructor(private readonly redis: RedisService) {}
|
2026-05-22 23:09:37 +08:00
|
|
|
|
2026-05-22 23:12:39 +08:00
|
|
|
async increment(key: string, ttl: number): Promise<{ totalHits: number; timeToExpire: number }> {
|
|
|
|
|
const redisKey = `throttle:${key}`;
|
2026-05-22 23:09:37 +08:00
|
|
|
try {
|
2026-05-22 23:12:39 +08:00
|
|
|
const result = await this.redis.incr(redisKey);
|
2026-05-22 23:09:37 +08:00
|
|
|
await this.redis.expire(redisKey, Math.ceil(ttl / 1000));
|
2026-05-22 23:12:39 +08:00
|
|
|
return { totalHits: result, timeToExpire: ttl };
|
2026-05-22 23:09:37 +08:00
|
|
|
} catch {
|
2026-05-22 23:12:39 +08:00
|
|
|
return { totalHits: 1, timeToExpire: ttl };
|
2026-05-22 23:09:37 +08:00
|
|
|
}
|
2026-05-22 23:09:16 +08:00
|
|
|
}
|
|
|
|
|
}
|