-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathserver.js
More file actions
75 lines (59 loc) · 1.95 KB
/
server.js
File metadata and controls
75 lines (59 loc) · 1.95 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
66
67
68
69
70
71
72
73
74
75
'use strict'
const http = require('http')
const express = require('express');
const app = express();
const path = require('path');
const environment = process.env.NODE_ENV || 'development';
const bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.set('port', process.env.PORT || 3000);
app.locals.title = 'Real Time';
app.locals.polls = [];
app.locals.answers = [[], [], [], []];
app.locals.votes = {}
const votes = {}
const voteCount = {}
app.use(express.static(path.join(__dirname, '/public')));
const port = process.env.PORT || 3000;
const server = http.createServer(app)
.listen(port, () => {
console.log(`Listening on port ${port}.`)
});
const socketIo = require('socket.io');
const io = socketIo(server);
app.get('/', (request, response) => {
response.sendfile(__dirname + '/public/index.html')
})
app.get('/poll', (request, response) => {
response.sendfile(__dirname + '/public/poll.html')
})
app.get('/api/polls', (request, response) => {
response.send(app.locals.polls)
});
app.post('/api/polls', (request, response) => {
app.locals.polls = []
app.locals.polls.push(request.body);
response.send(app.locals.polls);
});
io.on('connection', (socket) => {
io.sockets.emit('votes', app.locals.answers)
io.sockets.emit('usersConnected', io.engine.clientsCount);
socket.on('message', (channel, message) => {
if(channel === 'voteCast') {
app.locals.answers = app.locals.answers.map((answer) => {
return answer.filter((vote) => {
return vote !== message.photoUrl
})
})
app.locals.answers[message.id].push(message.photoUrl)
let votes = app.locals.answers[message.id]
io.sockets.emit('votes', app.locals.answers);
}
});
socket.on('disconnect', () => {
console.log('A user has disconnected.', io.engine.clientsCount);
io.sockets.emit('usersConnected', io.engine.clientsCount);
});
});
module.exports = app;