-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
88 lines (72 loc) · 2.54 KB
/
server.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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
// Require needed modules and initialize Express app
const express = require('express');
// CORS for Cross-Origin Resource Sharing
const cors = require('cors');
const app = express();
// Middleware for GET /events endpoint
function eventsHandler(req, res, next) {
// Mandatory headers and http status to keep connection open
const headers = {
'Content-Type': 'text/event-stream',
'Connection': 'keep-alive',
'Cache-Control': 'no-cache'
};
res.writeHead(200, headers);
// After client opens connection send all nests as string
const data = `data: ${JSON.stringify(questions)}\n\n`;
res.write(data);
res.flushHeaders();
// Generate an id based on timestamp and save res
// object of client connection on clients list
// Later we'll iterate it and send updates to each client
const clientId = Date.now();
const newClient = {
id: clientId,
res
};
clients.push(newClient);
// When client closes connection we update the clients list
// avoiding the disconnected one
req.on('close', () => {
console.log(`${clientId} Connection closed`);
clients = clients.filter(c => c.id !== clientId);
});
}
// Iterate clients list and use write res object method to send visible
function sendEventsToAll(json) {
clients.forEach(c => c.res.write(`data: ${JSON.stringify(json)}\n\n`))
}
// Middleware for POST /question endpoint
async function addQuestion(req, res, next) {
const newQuestion = req.body;
try {
if (newQuestion.IsValid === true) {
delete newQuestion.IsValid;
questions.push(newQuestion);
// Send recently added question as POST result
res.json(newQuestion)
// Invoke iterate and send function
return sendEventsToAll(newQuestion);
} else {
// Throw an error if it isn't valid
throw ErrorEvent();
}
} catch (error) {
// Return an empty 200 message
res.json(error);
return error;
}
}
// Set cors and bodyParser middlewares
app.use(cors());
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
// Define endpoints
app.post('/question', addQuestion);
app.get('/events', eventsHandler);
app.get('/status', (req, res) => res.json({ clients: clients.length }));
const PORT = process.env.PORT || 3001;
let clients = [];
let questions = [];
// Start server on 3001 port
app.listen(PORT, function () { console.log(`Question service listening on port ${PORT}`); });