Skip to content

Commit

Permalink
Merge pull request dockersamples#56 from docker/revert-54-connection_…
Browse files Browse the repository at this point in the history
…pooling

Revert "added connection pooling to postgres to prevent client timeouts"
  • Loading branch information
Mano Marks committed Dec 27, 2016
2 parents feacab9 + 9352ed0 commit 0334f60
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 15 deletions.
1 change: 0 additions & 1 deletion result/package.json
Expand Up @@ -15,7 +15,6 @@
"method-override": "^2.3.5",
"async": "^1.5.0",
"pg": "^4.4.3",
"pg-pool": "1.6.0",
"socket.io": "^1.3.7"
}
}
35 changes: 21 additions & 14 deletions result/server.js
@@ -1,25 +1,13 @@
var express = require('express'),
async = require('async'),
pg = require("pg"),
Pool = require("pg-pool"),
cookieParser = require('cookie-parser'),
bodyParser = require('body-parser'),
bodyParser = require('body-parser'),
methodOverride = require('method-override'),
app = express(),
server = require('http').Server(app),
io = require('socket.io')(server);

var config = {
host: 'localhost',
user: 'postgres',
password: '',
database: 'postgres',
max: 10, // max number of clients in pool
idleTimeoutMillis: 1000, // close & remove clients which have been idle > 1 second
};

var client = new Pool(config)

io.set('transports', ['polling']);

var port = process.env.PORT || 4000;
Expand All @@ -35,6 +23,14 @@ io.sockets.on('connection', function (socket) {

async.retry(
{times: 1000, interval: 1000},
function(callback) {
pg.connect('postgres://postgres@db/postgres', function(err, client, done) {
if (err) {
console.error("Waiting for db");
}
callback(err, client);
});
},
function(err, client) {
if (err) {
return console.err("Giving up");
Expand All @@ -49,13 +45,24 @@ function getVotes(client) {
if (err) {
console.error("Error performing query: " + err);
} else {
var votes = result.rows[0].count
var votes = collectVotesFromResult(result);
io.sockets.emit("scores", JSON.stringify(votes));
}

setTimeout(function() {getVotes(client) }, 1000);
});
}

function collectVotesFromResult(result) {
var votes = {a: 0, b: 0};

result.rows.forEach(function (row) {
votes[row.vote] = parseInt(row.count);
});

return votes;
}

app.use(cookieParser());
app.use(bodyParser());
app.use(methodOverride('X-HTTP-Method-Override'));
Expand Down

0 comments on commit 0334f60

Please sign in to comment.