mirror of
https://gitlab.com/wgp/dougal/software.git
synced 2025-12-06 10:57:07 +00:00
Add websocket server to emit DB notifications
This commit is contained in:
41
lib/www/server/ws/db.js
Normal file
41
lib/www/server/ws/db.js
Normal 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
|
||||
}
|
||||
Reference in New Issue
Block a user