const Redis = require('ioredis'); let redis = null; let ttl = 30; function init() { if (redis) { redis.disconnect(); } const host = process.env.VALKEY_HOST || 'localhost'; const port = parseInt(process.env.VALKEY_PORT) || 6379; const password = process.env.VALKEY_PASSWORD || undefined; const db = parseInt(process.env.VALKEY_DB) || 0; ttl = parseInt(process.env.VALKEY_TTL) || 30; try { redis = new Redis({ host, port, password, db, lazyConnect: true, maxRetriesPerRequest: 1 }); redis.on('error', (err) => { // Fail silently after one retry, we just won't cache console.warn('[Cache] Valkey connection failed, caching disabled:', err.message); }); } catch (err) { console.warn('[Cache] Valkey init failed:', err.message); } } init(); const cache = { init, async get(key) { if (!redis) return null; try { const data = await redis.get(key); return data ? JSON.parse(data) : null; } catch (e) { return null; } }, async set(key, value, customTtl = ttl) { if (!redis) return; try { await redis.set(key, JSON.stringify(value), 'EX', customTtl); } catch (e) { // ignore } }, async del(key) { if (!redis) return; try { await redis.del(key); } catch (e) { // ignore } }, async checkHealth() { if (!redis) return { status: 'down', error: 'Valkey client not initialized' }; try { const result = await redis.ping(); if (result === 'PONG') return { status: 'up' }; return { status: 'down', error: 'Invalid ping response' }; } catch (e) { return { status: 'down', error: e.message }; } } }; module.exports = cache;