mirror of
https://gitlab.com/wgp/dougal/software.git
synced 2025-12-06 10:57:07 +00:00
The events listener now listens to the 'end' event from the PostgreSQL driver and will attempt to reconnect if we get disconnected.
59 lines
1.3 KiB
JavaScript
59 lines
1.3 KiB
JavaScript
const { pool } = require('../lib/db/connection');
|
|
|
|
var client;
|
|
|
|
const channels = {};
|
|
|
|
async function notify (data) {
|
|
if (data.channel in channels) {
|
|
data._received = new Date();
|
|
try {
|
|
const json = JSON.parse(data.payload);
|
|
data.payload = json;
|
|
} catch {
|
|
// Ignore the error
|
|
}
|
|
for (const listener of channels[data.channel]) {
|
|
listener(JSON.parse(JSON.stringify(data)));
|
|
}
|
|
}
|
|
}
|
|
|
|
function reconnect () {
|
|
console.log("Reconnecting");
|
|
// No need to provide parameters, channels should already be populated.
|
|
listen();
|
|
}
|
|
|
|
async function listen (addChannels, callback) {
|
|
if (!client) {
|
|
client = await pool.connect();
|
|
client.on('notification', notify);
|
|
console.log("Client connected");
|
|
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");
|
|
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);
|
|
}
|
|
|
|
channels[channel].push(callback);
|
|
}
|
|
}
|
|
|
|
module.exports = {
|
|
listen
|
|
}
|