From 424f789706f8bb4f0ae3187b209f16e297b2a67b Mon Sep 17 00:00:00 2001 From: Brian C Date: Tue, 21 Jun 2016 10:02:52 -0500 Subject: [PATCH] Updated Example (markdown) --- Example.md | 66 +++++++++++++++++++++--------------------------------- 1 file changed, 26 insertions(+), 40 deletions(-) diff --git a/Example.md b/Example.md index e59cb46..0710978 100644 --- a/Example.md +++ b/Example.md @@ -4,55 +4,41 @@ You'll need to first "create table visit (date date)" in your postgres database ```javascript var http = require('http'); -var pg = require('pg'); +var Pool = require('pg').Pool; -var conString = "postgres://postgres@localhost:5432/postgres"; +// by default the pool will use the same environment variables +// as psql, pg_dump, pg_restore etc: +// https://www.postgresql.org/docs/9.5/static/libpq-envars.html + +// you can optionally supply other values +var config = { + host: 'localhost', + user: 'foo', + password: 'bar', + database: 'my_db', +}; + +var pool = new Pool(config) var server = http.createServer(function(req, res) { - // get a pg client from the connection pool - pg.connect(conString, function(err, client, done) { + var onError = function() { + res.writeHead(500, {'content-type': 'text/plain'}); + res.end('An error occurred'); + }; - var handleError = function(err) { - // no error occurred, continue with the request - if(!err) return false; + pool.query('INSERT INTO visit (date) VALUES ($1)', [new Date()], function(err) { + if (err) return onError(); - // An error occurred, remove the client from the connection pool. - // A truthy value passed to done will remove the connection from the pool - // instead of simply returning it to be reused. - // In this case, if we have successfully received a client (truthy) - // then it will be removed from the pool. - if(client){ - done(client); - } - res.writeHead(500, {'content-type': 'text/plain'}); - res.end('An error occurred'); - return true; - }; - - // handle an error from the connection - if(handleError(err)) return; - - // record the visit - client.query('INSERT INTO visit (date) VALUES ($1)', [new Date()], function(err, result) { - + // get the total number of visits today (including the current visit) + pool.query('SELECT COUNT(date) AS count FROM visit', function(err, result) { // handle an error from the query - if(handleError(err)) return; - - // get the total number of visits today (including the current visit) - client.query('SELECT COUNT(date) AS count FROM visit', function(err, result) { - - // handle an error from the query - if(handleError(err)) return; - - // return the client to the connection pool for other requests to reuse - done(); - res.writeHead(200, {'content-type': 'text/plain'}); - res.end('You are visitor number ' + result.rows[0].count); - }); + if(err) return onError(); + res.writeHead(200, {'content-type': 'text/plain'}); + res.end('You are visitor number ' + result.rows[0].count); }); }); -}) +}); server.listen(3001) ```