2026-03-10 22:11:47 +01:00
|
|
|
import { createClient, type RedisClientType } from 'redis';
|
2025-11-01 15:49:29 +01:00
|
|
|
import { env } from '@api/config/env';
|
2025-09-21 19:35:41 +01:00
|
|
|
|
2026-03-09 11:18:22 +01:00
|
|
|
// Create Redis client
|
2026-03-10 22:11:47 +01:00
|
|
|
const client: RedisClientType = createClient({
|
2026-03-09 11:18:22 +01:00
|
|
|
url: env.REDIS_URL
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
// Handle connection events
|
|
|
|
|
client.on('error', (err) => {
|
|
|
|
|
console.error('Redis Client Error:', err);
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
client.on('connect', () => {
|
|
|
|
|
console.log('Redis Client Connected');
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
client.on('reconnecting', () => {
|
|
|
|
|
console.log('Redis Client Reconnecting');
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
// Track connection state
|
|
|
|
|
let isConnected = false;
|
|
|
|
|
|
|
|
|
|
export async function connectRedis(): Promise<void> {
|
2026-03-11 12:57:44 +01:00
|
|
|
if (!env.REDIS_URL) {
|
|
|
|
|
console.warn('REDIS_URL not set, Redis features disabled');
|
|
|
|
|
return;
|
|
|
|
|
}
|
|
|
|
|
if (isConnected) return;
|
|
|
|
|
try {
|
2026-03-09 11:18:22 +01:00
|
|
|
await client.connect();
|
|
|
|
|
isConnected = true;
|
2026-03-11 12:57:44 +01:00
|
|
|
} catch (error) {
|
|
|
|
|
console.error('Redis connection failed, API will run without Redis:', error);
|
|
|
|
|
// Don't throw - allow API to start; rate limiting and caching will degrade gracefully
|
2026-03-09 11:18:22 +01:00
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Export the client (connection will be established before server starts)
|
2026-03-10 22:11:47 +01:00
|
|
|
export const redis: RedisClientType = client;
|
2026-03-09 11:18:22 +01:00
|
|
|
|
|
|
|
|
// Export type for use in other files
|
2026-03-10 22:11:47 +01:00
|
|
|
export type RedisClient = RedisClientType;
|