2015-11-15 20:59:29 +01:00
|
|
|
var express = require('express'),
|
|
|
|
async = require('async'),
|
|
|
|
pg = require("pg"),
|
|
|
|
cookieParser = require('cookie-parser'),
|
|
|
|
bodyParser = require('body-parser'),
|
|
|
|
methodOverride = require('method-override'),
|
|
|
|
app = express(),
|
|
|
|
server = require('http').Server(app),
|
|
|
|
io = require('socket.io')(server);
|
|
|
|
|
|
|
|
io.set('transports', ['polling']);
|
|
|
|
|
|
|
|
var port = process.env.PORT || 4000;
|
|
|
|
|
|
|
|
io.sockets.on('connection', function (socket) {
|
|
|
|
|
|
|
|
socket.emit('message', { text : 'Welcome!' });
|
|
|
|
|
|
|
|
socket.on('subscribe', function (data) {
|
|
|
|
socket.join(data.channel);
|
|
|
|
});
|
|
|
|
});
|
|
|
|
|
|
|
|
async.retry(
|
|
|
|
{times: 1000, interval: 1000},
|
|
|
|
function(callback) {
|
2016-01-25 19:20:23 +01:00
|
|
|
pg.connect('postgres://postgres@db/postgres', function(err, client, done) {
|
2015-11-15 20:59:29 +01:00
|
|
|
if (err) {
|
|
|
|
console.error("Failed to connect to db");
|
|
|
|
}
|
|
|
|
callback(err, client);
|
|
|
|
});
|
|
|
|
},
|
|
|
|
function(err, client) {
|
|
|
|
if (err) {
|
|
|
|
return console.err("Giving up");
|
|
|
|
}
|
|
|
|
console.log("Connected to db");
|
|
|
|
getVotes(client);
|
|
|
|
}
|
|
|
|
);
|
|
|
|
|
|
|
|
function getVotes(client) {
|
|
|
|
client.query('SELECT vote, COUNT(id) AS count FROM votes GROUP BY vote', [], function(err, result) {
|
|
|
|
if (err) {
|
|
|
|
console.error("Error performing query: " + err);
|
|
|
|
} else {
|
2016-06-09 12:48:19 +02:00
|
|
|
var votes = collectVotesFromResult(result);
|
|
|
|
io.sockets.emit("scores", JSON.stringify(votes));
|
2015-11-15 20:59:29 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
setTimeout(function() {getVotes(client) }, 1000);
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
2016-06-09 12:48:19 +02:00
|
|
|
function collectVotesFromResult(result) {
|
|
|
|
var votes = {a: 0, b: 0};
|
|
|
|
|
|
|
|
result.rows.forEach(function (row) {
|
|
|
|
votes[row.vote] = parseInt(row.count);
|
|
|
|
});
|
|
|
|
|
|
|
|
return votes;
|
|
|
|
}
|
|
|
|
|
2015-11-15 20:59:29 +01:00
|
|
|
app.use(cookieParser());
|
|
|
|
app.use(bodyParser());
|
|
|
|
app.use(methodOverride('X-HTTP-Method-Override'));
|
|
|
|
app.use(function(req, res, next) {
|
|
|
|
res.header("Access-Control-Allow-Origin", "*");
|
|
|
|
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
|
|
|
|
res.header("Access-Control-Allow-Methods", "PUT, GET, POST, DELETE, OPTIONS");
|
|
|
|
next();
|
|
|
|
});
|
|
|
|
|
|
|
|
app.use(express.static(__dirname + '/views'));
|
|
|
|
|
|
|
|
app.get('/', function (req, res) {
|
|
|
|
res.sendFile(path.resolve(__dirname + '/views/index.html'));
|
|
|
|
});
|
|
|
|
|
|
|
|
server.listen(port, function () {
|
|
|
|
var port = server.address().port;
|
|
|
|
console.log('App running on port ' + port);
|
|
|
|
});
|