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
|
|
|
|
|
});
|
|
|
|
|
|
2026-03-30 08:24:55 +01:00
|
|
|
let hasLoggedRedisUnavailable = false;
|
|
|
|
|
|
|
|
|
|
export function logRedisUnavailableOnce(message: string, error?: unknown): void {
|
|
|
|
|
if (hasLoggedRedisUnavailable) {
|
|
|
|
|
return;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
hasLoggedRedisUnavailable = true;
|
|
|
|
|
|
|
|
|
|
if (error) {
|
|
|
|
|
console.warn(message, error);
|
|
|
|
|
return;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
console.warn(message);
|
|
|
|
|
}
|
|
|
|
|
|
2026-03-09 11:18:22 +01:00
|
|
|
// Handle connection events
|
|
|
|
|
client.on('error', (err) => {
|
2026-03-30 08:24:55 +01:00
|
|
|
logRedisUnavailableOnce('Redis unavailable, Redis-backed features disabled', err);
|
2026-03-09 11:18:22 +01:00
|
|
|
});
|
|
|
|
|
|
|
|
|
|
client.on('connect', () => {
|
|
|
|
|
console.log('Redis Client Connected');
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
// Track connection state
|
|
|
|
|
let isConnected = false;
|
|
|
|
|
|
|
|
|
|
export async function connectRedis(): Promise<void> {
|
2026-03-11 12:57:44 +01:00
|
|
|
if (!env.REDIS_URL) {
|
2026-03-30 08:24:55 +01:00
|
|
|
logRedisUnavailableOnce('REDIS_URL not set, Redis features disabled');
|
2026-03-11 12:57:44 +01:00
|
|
|
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) {
|
2026-03-30 08:24:55 +01:00
|
|
|
logRedisUnavailableOnce('Redis connection failed, API will run without Redis', error);
|
2026-03-11 12:57:44 +01:00
|
|
|
// 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;
|