Spaces:
Paused
Paused
File size: 1,701 Bytes
c0b3afa | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 | const { createClient } = require('redis');
const log = require('./logger');
let redisUnavailable = false;
let hasLoggedError = false;
const redisClient = createClient({
socket: {
host: process.env.REDIS_HOST || 'localhost',
port: process.env.REDIS_PORT || 6379,
},
password: process.env.REDIS_PASSWORD || null,
});
redisClient.on('ready', () => {
if (redisUnavailable) {
redisUnavailable = false;
hasLoggedError = false;
log.info('Redis is ready and connected.');
}
});
redisClient.on('end', () => {
if (!redisUnavailable) {
redisUnavailable = true;
log.warn('Redis connection closed. Marking as unavailable.');
}
});
redisClient.on('error', (err) => {
if (!redisUnavailable) {
redisUnavailable = true;
}
if (!hasLoggedError) {
log.error(`Redis error: ${err}. Marking Redis as unavailable.`);
hasLoggedError = true;
}
});
redisClient.connect().catch((err) => {
if (!hasLoggedError) {
log.error(`Failed to connect to Redis: ${err}. Disabling Redis cache temporarily.`);
hasLoggedError = true;
}
redisUnavailable = true;
});
const safeRedisCall = async (operation, ...args) => {
if (redisUnavailable) {
log.warn('Redis is unavailable, skipping cache operation.');
return null;
}
try {
return await redisClient[operation](...args);
} catch (err) {
if (!redisUnavailable) {
redisUnavailable = true;
log.error(`Redis operation failed: ${err}. Marking Redis as unavailable.`);
}
return null;
}
};
module.exports = {
redisClient,
safeRedisCall
};
|