Files
pagodera/lib/redis/index.ts
T
Evandro Fonseca Junior 55eebde0ba feat: add user authentication UI to header component
Add login and register dialogs, user dropdown menu with profile link and logout option, and integrate with session management hook. Prevent hydration mismatches by conditionally rendering auth elements after mount. Update package-lock.json with new @esbuild dependencies for build tooling.
2025-11-04 02:33:29 -03:00

97 lines
2.0 KiB
TypeScript

/**
* Módulo de conexão com Redis
* Gerencia conexão e fornece helpers para cache e sessões
*/
import { createClient, RedisClientType } from "redis";
let client: RedisClientType | null = null;
/**
* Valida variáveis de ambiente necessárias
*/
function validateEnvVars() {
if (!process.env.REDIS_DB) {
throw new Error(
"REDIS_DB não está definido. Configure a variável de ambiente REDIS_DB com a connection string do Redis."
);
}
}
/**
* Obtém ou cria o cliente Redis
*/
export function getRedisClient(): RedisClientType {
if (!client) {
validateEnvVars();
const connectionString = process.env.REDIS_DB;
client = createClient({
url: connectionString,
});
// Event listeners para debug
client.on("error", (err) => {
console.error("❌ Erro no cliente Redis:", err);
});
client.on("connect", () => {
console.log("✅ Conectado ao Redis");
});
client.on("ready", () => {
console.log("✅ Redis está pronto para uso");
});
// Conectar
client.connect().catch((err) => {
console.error("❌ Erro ao conectar com Redis:", err);
});
}
return client;
}
/**
* Verifica se Redis está conectado
*/
export async function isRedisConnected(): Promise<boolean> {
try {
const redisClient = getRedisClient();
if (!redisClient.isOpen) {
await redisClient.connect();
}
await redisClient.ping();
return true;
} catch (error) {
console.error("❌ Redis não está conectado:", error);
return false;
}
}
/**
* Fecha conexão com Redis
*/
export async function closeRedis(): Promise<void> {
if (client && client.isOpen) {
await client.quit();
client = null;
console.log("🔌 Conexão Redis fechada");
}
}
// Cleanup ao encerrar o processo
if (typeof process !== "undefined") {
process.on("SIGINT", async () => {
await closeRedis();
process.exit(0);
});
process.on("SIGTERM", async () => {
await closeRedis();
process.exit(0);
});
}