-
Notifications
You must be signed in to change notification settings - Fork 3
/
socket.js
75 lines (57 loc) · 1.93 KB
/
socket.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
69
70
71
72
73
const socketio = require('socket.io');
const cors = require('cors');
let ejs = require('ejs');
const buildWebsocket = (http, app, alertsTable) => {
let sockets = [];
let io = socketio(http);
io.on("connection", socket => {
console.log("user connected!");
// let liveAlerts = await getAlerts(alertsTable, false);
sockets.push(socket);
console.log(socket.id);
// let alertObject = await getAlertObject(liveAlerts);
// don't need to send new connections the alerts, as the alerts are sent with the HTML
// socket.emit("message", alertObject);
});
// have to enable CORS to allow airtable script to call
app.get("/admin/update-alerts", cors(), async (req, res) => {
let liveAlerts = await getAlerts(alertsTable, false);
let alertObject = await getAlertObject(liveAlerts);
io.emit("message", alertObject);
res.send("Alerts Updated!");
});
app.get('/admin/force-reload', cors(), async (req, res) => {
io.emit("message", {
type: "reload"
});
res.send("Forced Reload!");
});
}
const getAlertObject = async (alerts) => {
let html = "";
await alerts.forEach(async alert => {
let alertHtml = await ejs.renderFile('./views/partials/alert.ejs', alert);
html += alertHtml;
});
return {
type: "alerts",
body: alerts,
html: html
}
}
const getAlerts = async (alertsTable, testStatus = false) => {
let allAlerts = await alertsTable.read();
let liveAlerts = allAlerts.filter(alert => alert.fields.Status == "Deployed" || (alert.fields.Status == "Test Deployed" && testStatus));
return liveAlerts.map(alert => {
return {
head: alert.fields.Header,
body: alert.fields.Body,
category: alert.fields.Category
}
});
}
module.exports = {
buildWebsocket,
getAlertObject,
getAlerts
}