server.js 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. var express = require('express'),
  2. async = require('async'),
  3. { Pool } = require('pg'),
  4. cookieParser = require('cookie-parser'),
  5. app = express(),
  6. server = require('http').Server(app),
  7. io = require('socket.io')(server);
  8. var port = process.env.PORT || 4000;
  9. io.on('connection', function (socket) {
  10. socket.emit('message', { text : 'Welcome!' });
  11. socket.on('subscribe', function (data) {
  12. socket.join(data.channel);
  13. });
  14. });
  15. var pool = new Pool({
  16. connectionString: 'postgres://postgres:postgres@db/postgres'
  17. });
  18. async.retry(
  19. {times: 1000, interval: 1000},
  20. function(callback) {
  21. pool.connect(function(err, client, done) {
  22. if (err) {
  23. console.error("Waiting for db");
  24. }
  25. callback(err, client);
  26. });
  27. },
  28. function(err, client) {
  29. if (err) {
  30. return console.error("Giving up");
  31. }
  32. console.log("Connected to db");
  33. getVotes(client);
  34. }
  35. );
  36. function getVotes(client) {
  37. client.query('SELECT vote, COUNT(id) AS count FROM votes GROUP BY vote', [], function(err, result) {
  38. if (err) {
  39. console.error("Error performing query: " + err);
  40. } else {
  41. var votes = collectVotesFromResult(result);
  42. io.sockets.emit("scores", JSON.stringify(votes));
  43. }
  44. setTimeout(function() {getVotes(client) }, 1000);
  45. });
  46. }
  47. function collectVotesFromResult(result) {
  48. var votes = {a: 0, b: 0};
  49. result.rows.forEach(function (row) {
  50. votes[row.vote] = parseInt(row.count);
  51. });
  52. return votes;
  53. }
  54. app.use(cookieParser());
  55. app.use(express.urlencoded());
  56. app.use(express.static(__dirname + '/views'));
  57. app.get('/', function (req, res) {
  58. res.sendFile(path.resolve(__dirname + '/views/index.html'));
  59. });
  60. server.listen(port, function () {
  61. var port = server.address().port;
  62. console.log('App running on port ' + port);
  63. });