Make websocket notifications await.

Not sure if this helps much. It might help with avoiding
out of order notifications and reducing the rate at which
the clients get spammed when importing database dumps and
such, but that hasn't been tested.
This commit is contained in:
D. Berge
2021-05-24 15:52:29 +02:00
parent 5af89050fb
commit 13da38b4cd

View File

@@ -5,6 +5,7 @@ var client;
const channels = {}; const channels = {};
async function notify (data) { async function notify (data) {
if (data.channel in channels) { if (data.channel in channels) {
data._received = new Date(); data._received = new Date();
try { try {
@@ -14,7 +15,7 @@ async function notify (data) {
// Ignore the error // Ignore the error
} }
for (const listener of channels[data.channel]) { for (const listener of channels[data.channel]) {
listener(JSON.parse(JSON.stringify(data))); await listener(JSON.parse(JSON.stringify(data)));
} }
} }
} }
@@ -39,10 +40,10 @@ async function listen (addChannels, callback) {
return; return;
} }
client.on('notification', notify); client.on('notification', notify);
console.log("Client connected", Object.keys(channels)); console.log("Websocket client connected", Object.keys(channels));
client.on('error', (err) => console.error("Events client error: ", err)); client.on('error', (err) => console.error("Events client error: ", err));
client.on('end', () => { client.on('end', () => {
console.warn("Events client disconnected. Will attempt to reconnect in five seconds"); console.warn("Websocket events client disconnected. Will attempt to reconnect in five seconds");
setImmediate(() => client = null); setImmediate(() => client = null);
setTimeout(reconnect, 5000); setTimeout(reconnect, 5000);
}); });