This repository has been archived by the owner on Jun 4, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
86 lines (75 loc) · 2.1 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
/*******************************
* Configuration
******************************/
// Basic app configuration
var pub = __dirname + '/public';
var port = 3000;
/*******************************
* Required modules
******************************/
// Express for http requests
var express = require('express');
var app = express.createServer();
//Socket.io for websocket requests
var io = require('socket.io').listen(app);
// Our database module
var db = require('./database');
/*******************************
* App
******************************/
// Configure Express
app.configure(function () {
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(express.static(pub));
app.use(express.errorHandler({
dumpExceptions: true,
showStack: true
}));
app.use(app.router);
});
// Respond to http get requests at "/" with the index.html page
app.get('/', function (req, res) {
res.sendFile(pub + "/index.html");
});
// Respond to http posts at "/vote" by trying to save the response
app.post('/vote', function (req, res) {
// Request body should contain the email, constituency and party fields we
// need to save the vote.
db.saveVote(req.body, function (err) {
if (err) {
console.log(err);
res.send(err.message, 500);
}
else {
res.send("Saved", 200);
}
});
});
//Respond to new websocket connections by returning the current votes
io.sockets.on('connection', function (socket) {
db.getCurrentVotes(function (err, currentVotes) {
if (!err) {
socket.emit('votes', currentVotes);
}
else {
console.log(err);
}
});
});
// Broadcast totals to all sockets every second
var votesInterval = setInterval(function () {
db.getCurrentVotes(function (err, currentVotes) {
if (!err) {
io.sockets.emit('votes', currentVotes);
}
else {
console.log(err);
}
});
}, 1000);
/*******************************
* Start the app
******************************/
// Start Express
app.listen(port);