api-server/src/common/throttle/redis-throttler.storage.ts

20 lines
707 B
TypeScript
Raw Normal View History

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
async increment(key: string, ttl: number): Promise<{ totalHits: number; timeToExpire: number }> {
const redisKey = `throttle:${key}`;
2026-05-22 23:09:37 +08:00
try {
const result = await this.redis.incr(redisKey);
2026-05-22 23:09:37 +08:00
await this.redis.expire(redisKey, Math.ceil(ttl / 1000));
return { totalHits: result, timeToExpire: ttl };
2026-05-22 23:09:37 +08:00
} catch {
return { totalHits: 1, timeToExpire: ttl };
2026-05-22 23:09:37 +08:00
}
}
}