-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
65 lines (48 loc) · 1.35 KB
/
server.js
File metadata and controls
65 lines (48 loc) · 1.35 KB
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
const express = require("express");
const cors = require("cors");
const app = express();
app.use(cors());
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.get("/status", (request, response) =>
response.json({ clients: clients.length })
);
const PORT = 3000;
let clients = [];
let facts = [];
function eventsHandler(request, response, next) {
const headers = {
"Content-Type": "text/event-stream",
Connection: "keep-alive",
"Cache-Control": "no-cache",
};
response.writeHead(200, headers);
const data = `data: ${JSON.stringify(facts)}\n\n`;
response.write(data);
const clientId = Date.now();
const newClient = {
id: clientId,
response,
};
clients.push(newClient);
request.on("close", () => {
console.log(`${clientId} Connection closed`);
clients = clients.filter((client) => client.id !== clientId);
});
}
app.get("/events", eventsHandler);
function sendEventsToAll(newFact) {
clients.forEach((client) =>
client.response.write(`data: ${JSON.stringify(newFact)}\n\n`)
);
}
async function addFact(request, respsonse, next) {
const newFact = request.body;
facts.push(newFact);
respsonse.json(newFact);
return sendEventsToAll(newFact);
}
app.post("/fact", addFact);
app.listen(PORT, () => {
console.log(`Facts Events service listening at http://localhost:${PORT}`);
});