import Redis from 'ioredis'; if (!process.env.REDIS_URL) { throw new Error('REDIS_URL não configurada'); } const redis = new Redis(process.env.REDIS_URL, { maxRetriesPerRequest: 3, retryStrategy(times) { const delay = Math.min(times * 50, 2000); return delay; }, reconnectOnError(err) { const targetError = 'READONLY'; if (err.message.includes(targetError)) { return true; } return false; } }); redis.on('error', (error) => { console.error('[Redis] Erro de conexão:', error); }); redis.on('connect', () => { console.log('[Redis] Conectado com sucesso'); }); export async function getFromCache(key: string): Promise { try { const cached = await redis.get(key); if (cached) { return JSON.parse(cached) as T; } return null; } catch (error) { console.error('[Redis] Erro ao buscar do cache:', error); return null; } } export async function setInCache(key: string, value: any, expireInSeconds = 3600): Promise { try { await redis.set(key, JSON.stringify(value), 'EX', expireInSeconds); } catch (error) { console.error('[Redis] Erro ao salvar no cache:', error); } } export async function invalidateCache(pattern: string): Promise { try { const keys = await redis.keys(pattern); if (keys.length > 0) { await redis.del(...keys); } } catch (error) { console.error('[Redis] Erro ao invalidar cache:', error); } } export default redis;