I have an express database that connects to multiple redis servers by receiving the connection ip from a client.
It works fine if the redis database exists. The problem im facing is that if the ip doesnt exist, I will receive a
Error: Error: Redis connection to xxxx failed - connect ECONNREFUSED xxx
Being this totally understandable, but the problem is that my connection object is still defined. And i cant really seem how to identify this object as a failed connection.
The only hint i might have might be in the connection._events.error variable, but it returns a [Function]
This is my code
let connections = []
const killRedis = (redisClient, ip, port) => {
redisClient.quit()
connections = connections.filter((i) => { return i.ip !== ip && i.port != port })
}
const subscribe = (redisClient, url, port) => {
redisClient.on('error', function (err) {
//this is supposed to handle the error, but i dont know how to make the "undefined" value available for the createRedisClient function. Since this seems to be delayed
killRedis(redisClient, url, port)
return undefined;
});
redisClient.on('connect', function () {
console.log('Connected to Redis');
return redisClient;
});
}
findConnection = (ip, port) => {
let connection = connections.filter(i => i.ip == ip && i.port == port)
if (connection && connection.length > 0) {
return connection[0].connection
} else {
connections.push({
ip: ip,
port: port,
connection: require('redis').createClient(port, ip, {
no_ready_check: true,
db: 1
})
})
let pushedConnection = connections.filter(i => i.ip == ip && i.port == port)[0].connection
subscribe(pushedConnection, ip, port)
return pushedConnection
}
}
const createRedisClient = async (port, url) => {
let redisClient = findConnection(url, port)
console.log(redisClient._events.error) //[Function]
return redisClient // this is always a connection object, even if the connection is faulty
}
module.exports = { createRedisClient }