-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
79 lines (67 loc) · 2.16 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
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;
var db_host = process.env.DB_HOST || db;
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) {
pg.connect('postgres://postgres@' + db_host + '/postgres', function(err, client, done) {
if (err) {
console.error("Failed to connect to db (" + db_host + ")");
}
callback(err, client);
});
},
function(err, client) {
if (err) {
return console.err("Giving up");
}
console.log("Connected to db (" + db_host + ")");
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 {
var data = result.rows.reduce(function(obj, row) {
obj[row.vote] = row.count;
return obj;
}, {});
io.sockets.emit("scores", JSON.stringify(data));
}
setTimeout(function() {getVotes(client) }, 1000);
});
}
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);
});