Modularize NodeJs Connection with PostgreSQL

0

I'm having trouble creating a module in nodejs to export my connection to PostgreSQL .

I could not understand why the second code does not work because I would like to export connect already.

Code 1 .

var pg = require('pg');

module.exports = function () {
    var conString = 'postgres://usuario:senha@localhost:5432/teste';
    var conexao = new pg.Client(conString);
    return conexao;
};

I call this in my app:

var db = require('../../config/conexao');
var conexao = db();
conexao.connect();
conexao.query('select * from cliente', function (error, result) {..

Code 2

var pg = require('pg');

module.exports = function () {
    var conString = 'postgres://usuario:senha@localhost:5432/teste';
    var conexao = new pg.Client(conString);

    // retorna já a conexao feita 
    return conexao.connect();
};

And I call it that:

var conexao = db();
  

Without using connect , so I get the error that the query method does not   exists.

Because of the second way, I can not find the query method in my connection?

    
asked by anonymous 31.10.2017 / 02:57

1 answer

2

In the second code you are already exporting the object representing the connection. It is not necessary to invoke it as if it were a function.

So, instead of importing the module this way:

var conexao = db();

You can simply use:

var conexao = db;

    
31.10.2017 / 15:49