-
Notifications
You must be signed in to change notification settings - Fork 2
/
index.js
51 lines (42 loc) · 1.34 KB
/
index.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
const express = require('express');
const cors = require('cors');
const bodyParser = require('body-parser');
const { listen, listeners } = require('./server/tweetStreams');
const normalizer = require('./server/normalizer');
const http = require('http');
const WebSocket = require('ws');
const PORT = 8002;
const app = express();
app.use(cors());
app.use(bodyParser.json());
app.get('/test/:id', (req, res) => {
const param = req.param('id') || "";
const testTweet = require(`./server/tweet${param}.json`);
listeners.forEach((listener) => listener(testTweet));
res.json({ message: 'Sent test tweet trough websocket' });
});
const server = http.createServer(app);
const wss = new WebSocket.Server({ server, path: '/tweets' });
const clients = [];
wss.on('connection', function(ws) {
clients.push(ws);
console.log('New client joined');
});
clients.forEach((client) => {
client.on('error', (err) => {
console.error('Client error: ', err);
});
});
listen((data) => {
const normalizedData = normalizer(data);
console.log(data);
clients.forEach((client) => {
// console.log(client.readyState === WebSocket.OPEN, client.readyState);
if (client.readyState === WebSocket.OPEN) {
client.send(JSON.stringify(normalizedData));
}
});
});
server.listen(PORT, () => {
console.log(`App is running at http://localhost:${PORT}`);
});