60 lines
1.2 KiB
JavaScript
60 lines
1.2 KiB
JavaScript
const Redis = require('ioredis');
|
|
|
|
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;
|
|
const ttl = parseInt(process.env.VALKEY_TTL) || 30;
|
|
|
|
let redis = null;
|
|
|
|
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);
|
|
}
|
|
|
|
const cache = {
|
|
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
|
|
}
|
|
}
|
|
};
|
|
|
|
module.exports = cache;
|