Catch DB connection errors.

If we can't connect straight away (either first time
or after a disconnection), keep retrying until we
manage.
This commit is contained in:
D. Berge
2020-10-06 19:44:07 +02:00
parent 2486cb3944
commit eb6329e6f7

View File

@@ -27,29 +27,41 @@ function reconnect () {
async function listen (addChannels, callback) {
if (!client) {
client = await pool.connect();
try {
client = await pool.connect();
} catch (err) {
console.error("Error connecting to DB", err);
console.log("Will try again in 15 seconds");
setImmediate(() => client = null);
setTimeout(() => {
listen(addChannels, callback);
}, 15000);
return;
}
client.on('notification', notify);
console.log("Client connected");
console.log("Client connected", Object.keys(channels));
client.on('error', (err) => console.error("Events client error: ", err));
client.on('end', () => {
console.warning("Events client disconnected. Will attempt to reconnect in five seconds");
console.warn("Events client disconnected. Will attempt to reconnect in five seconds");
setImmediate(() => client = null);
setTimeout(reconnect, 5000);
});
}
if (addChannels && !Array.isArray(addChannels)) {
addChannels = [addChannels];
}
for (const channel of addChannels) {
if (!(channel in channels)) {
await client.query("LISTEN "+channel);
channels[channel] = [];
console.log("Listening to ", channel);
if (addChannels) {
if (!Array.isArray(addChannels)) {
addChannels = [addChannels];
}
channels[channel].push(callback);
for (const channel of addChannels) {
if (!(channel in channels)) {
await client.query("LISTEN "+channel);
channels[channel] = [];
console.log("Listening to ", channel);
}
channels[channel].push(callback);
}
}
}