UNPKG

recoder-code

Version:

🚀 AI-powered development platform - Chat with 32+ models, build projects, automate workflows. Free models included!

36 lines (28 loc) • 1.09 kB
/** * Rate Limiting Service */ import { getRedis } from '../redis'; export class RateLimitService { private redis = getRedis(); async checkRateLimit(key: string, limit: number, window: number): Promise<{ allowed: boolean; remaining: number }> { const current = await this.redis.get(key); if (!current) { await this.redis.setex(key, window, '1'); return { allowed: true, remaining: limit - 1 }; } const count = parseInt(current); if (count >= limit) { return { allowed: false, remaining: 0 }; } await this.redis.incr(key); return { allowed: true, remaining: limit - count - 1 }; } async getUserRateLimit(userId: string): Promise<{ allowed: boolean; remaining: number }> { const key = `rate_limit:user:${userId}`; return this.checkRateLimit(key, 1000, 3600); // 1000 requests per hour } async getApiKeyRateLimit(apiKey: string): Promise<{ allowed: boolean; remaining: number }> { const key = `rate_limit:api_key:${apiKey}`; return this.checkRateLimit(key, 5000, 3600); // 5000 requests per hour } }