Add websocket server to emit DB notifications

This commit is contained in:
D. Berge
2020-09-03 14:04:29 +02:00
parent 8c6d4e69ac
commit 52907921f1
5 changed files with 99 additions and 2 deletions

41
lib/www/server/ws/db.js Normal file
View File

@@ -0,0 +1,41 @@
const { pool } = require('../lib/db/connection');
var client;
const channels = {};
async function notify (data) {
console.log("NOTIFY", data);
if (data.channel in channels) {
data._received = new Date();
for (const listener of channels[data.channel]) {
listener(data);
}
}
}
async function listen (addChannels, callback) {
if (!client) {
client = await pool.connect();
client.on('notification', notify);
console.log("Client connected");
}
if (!Array.isArray(addChannels)) {
addChannels = [addChannels];
}
for (const channel of addChannels) {
if (!(channel in channels)) {
await client.query("LISTEN "+channel);
channels[channel] = new Set();
console.log("Listening to ", channel);
}
channels[channel].add(callback);
}
}
module.exports = {
listen
}