-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
68 lines (58 loc) · 1.54 KB
/
app.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
// Load in the .env file
require('dotenv').config();
// Websocket & Postgres Client packages
const WebSocket = require('ws');
const { Client } = require('pg');
// List of triggers we need from the database
const LISTEN_TRIGGERS = [
't_log',
't_messages',
't_configuration',
];
// Start our websocket
const wss = new WebSocket.Server({
port: 8080
});
// Broadcast to each client the payload and channel
function broadcast(channel, payload) {
wss.clients.forEach((client) => {
client.send(JSON.stringify({
channel: channel,
payload: payload,
}));
});
};
async function setupDatabaseConnection() {
const client = new Client();
await client.connect();
// Query the server to listen to our triggers
client.query(LISTEN_TRIGGERS.reduce((accumulator, trigger) => {
return `LISTEN ${trigger};${accumulator}`;
}, ''));
// When we receive a message
// Dispatch a message broadcast to the clients
client.on('notification', ({ channel, payload }) => {
// Set broadcast payload depending on message type
let rawPayload;
if(channel == 't_log' || channel == 't_configuration') {
rawPayload = JSON.parse(payload);
}
else {
rawPayload = 'message';
}
broadcast(channel, rawPayload);
});
}
// Every 10 seconds ping connected clients
// This is required to keep the connection open
// As browsers will terminate a websocket which hasn't
// communicated for some time
setInterval(() => {
wss.clients.forEach((client) => {
client.send(JSON.stringify({
channel: 'ping',
payload: 'hello',
}));
})
}, 10000);
setupDatabaseConnection();