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

14 lines
620 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) {}
async increment(key: string, ttl: number) {
const redisKey = `throttle:${key}`;
try { const hits = await this.redis.incr(redisKey); await this.redis.expire(redisKey, Math.ceil(ttl / 1000)); return { totalHits: hits, timeToExpire: ttl }; }
catch { return { totalHits: 1, timeToExpire: ttl }; }
}
}