1
1
var express = require ( 'express' ) ,
2
2
async = require ( 'async' ) ,
3
3
pg = require ( "pg" ) ,
4
- Pool = require ( "pg-pool" ) ,
5
4
cookieParser = require ( 'cookie-parser' ) ,
6
- bodyParser = require ( 'body-parser' ) ,
5
+ bodyParser = require ( 'body-parser' ) ,
7
6
methodOverride = require ( 'method-override' ) ,
8
7
app = express ( ) ,
9
8
server = require ( 'http' ) . Server ( app ) ,
10
9
io = require ( 'socket.io' ) ( server ) ;
11
10
12
- var config = {
13
- host : 'localhost' ,
14
- user : 'postgres' ,
15
- password : '' ,
16
- database : 'postgres' ,
17
- max : 10 , // max number of clients in pool
18
- idleTimeoutMillis : 1000 , // close & remove clients which have been idle > 1 second
19
- } ;
20
-
21
- var client = new Pool ( config )
22
-
23
11
io . set ( 'transports' , [ 'polling' ] ) ;
24
12
25
13
var port = process . env . PORT || 4000 ;
@@ -35,6 +23,14 @@ io.sockets.on('connection', function (socket) {
35
23
36
24
async . retry (
37
25
{ times : 1000 , interval : 1000 } ,
26
+ function ( callback ) {
27
+ pg . connect ( 'postgres://postgres@db/postgres' , function ( err , client , done ) {
28
+ if ( err ) {
29
+ console . error ( "Waiting for db" ) ;
30
+ }
31
+ callback ( err , client ) ;
32
+ } ) ;
33
+ } ,
38
34
function ( err , client ) {
39
35
if ( err ) {
40
36
return console . err ( "Giving up" ) ;
@@ -49,13 +45,24 @@ function getVotes(client) {
49
45
if ( err ) {
50
46
console . error ( "Error performing query: " + err ) ;
51
47
} else {
52
- var votes = result . rows [ 0 ] . count
48
+ var votes = collectVotesFromResult ( result ) ;
53
49
io . sockets . emit ( "scores" , JSON . stringify ( votes ) ) ;
54
50
}
51
+
55
52
setTimeout ( function ( ) { getVotes ( client ) } , 1000 ) ;
56
53
} ) ;
57
54
}
58
55
56
+ function collectVotesFromResult ( result ) {
57
+ var votes = { a : 0 , b : 0 } ;
58
+
59
+ result . rows . forEach ( function ( row ) {
60
+ votes [ row . vote ] = parseInt ( row . count ) ;
61
+ } ) ;
62
+
63
+ return votes ;
64
+ }
65
+
59
66
app . use ( cookieParser ( ) ) ;
60
67
app . use ( bodyParser ( ) ) ;
61
68
app . use ( methodOverride ( 'X-HTTP-Method-Override' ) ) ;
0 commit comments