1
1
var express = require ( 'express' ) ,
2
2
async = require ( 'async' ) ,
3
3
pg = require ( "pg" ) ,
4
+ Pool = require ( "pg-pool" ) ,
4
5
cookieParser = require ( 'cookie-parser' ) ,
5
- bodyParser = require ( 'body-parser' ) ,
6
+ bodyParser = require ( 'body-parser' ) ,
6
7
methodOverride = require ( 'method-override' ) ,
7
8
app = express ( ) ,
8
9
server = require ( 'http' ) . Server ( app ) ,
9
10
io = require ( 'socket.io' ) ( server ) ;
10
11
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
+
11
23
io . set ( 'transports' , [ 'polling' ] ) ;
12
24
13
25
var port = process . env . PORT || 4000 ;
@@ -23,14 +35,6 @@ io.sockets.on('connection', function (socket) {
23
35
24
36
async . retry (
25
37
{ 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
- } ,
34
38
function ( err , client ) {
35
39
if ( err ) {
36
40
return console . err ( "Giving up" ) ;
@@ -45,24 +49,13 @@ function getVotes(client) {
45
49
if ( err ) {
46
50
console . error ( "Error performing query: " + err ) ;
47
51
} else {
48
- var votes = collectVotesFromResult ( result ) ;
52
+ var votes = result . rows [ 0 ] . count
49
53
io . sockets . emit ( "scores" , JSON . stringify ( votes ) ) ;
50
54
}
51
-
52
55
setTimeout ( function ( ) { getVotes ( client ) } , 1000 ) ;
53
56
} ) ;
54
57
}
55
58
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
-
66
59
app . use ( cookieParser ( ) ) ;
67
60
app . use ( bodyParser ( ) ) ;
68
61
app . use ( methodOverride ( 'X-HTTP-Method-Override' ) ) ;
0 commit comments