Files
dougal-software/lib/www/server/ws/db.js

47 lines
903 B
JavaScript
Raw Normal View History

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)));
}
}
}
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] = [];
console.log("Listening to ", channel);
}
channels[channel].push(callback);
}
}
module.exports = {
listen
}