Postgres from node.js

I am using node-postgres in my application. I would like to learn the best practices that I want to follow in order to ensure a stable connection.

Below is the code I'm using right now,

exports.getAll = function (args, callback) { helper.client = new pg.Client('tcp://postgres:system6: 5432@192.168.143.11 /abc_dev'); helper.client.connect(); helper.client.query('select count(1) as total_records from facilities', function(err,response){ helper.client.query('select * ,'+response.rows[0].total_records+' as total_records from facilities', function(err,response){ callback(response); helper.client.end.bind(helper.client); }); }); }; 

As you can see in the code, I connect the database for each request and disconnects after the request is completed. I have another idea when I can connect the database globally only once and execute the query using an open connection. The code looks like

 helper.client = new pg.Client('tcp://postgres:system6: 5432@192.168.143.11 /abc_dev'); helper.client.connect(); exports.getAll = function (args, callback) { helper.client.query('select count(1) as total_records from facilities', function(err,response){ helper.client.query('select * ,'+response.rows[0].total_records+' as total_records from facilities', function(err,response){ callback(response); }); }); }; 

Here the connection never ends. As far as I know, I can’t decide which one is better. Please suggest.

Thanks..

+4
source share
1 answer

There is an example in the node-postgres wiki . It connects whenever a request is processed:

 var server = http.createServer(function(req, res, next) { pg.connect(function(err, client, done) { 

This is what I think is right: your connection should be in the request area.

+2
source

All Articles