mirror of
https://github.com/lucasrcsantana/story-generator.git
synced 2025-12-17 05:47:52 +00:00
- Implementa cliente Redis com retry e cache - Adiciona healthcheck da API - Configura tipagem para Next.js API routes - Implementa cache de histórias - Adiciona tratamento de erros robusto - Configura monitoramento de conexões - Otimiza performance com cache distribuído
62 lines
1.5 KiB
TypeScript
62 lines
1.5 KiB
TypeScript
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<T>(key: string): Promise<T | null> {
|
|
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<void> {
|
|
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<void> {
|
|
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;
|