Modularize Nodejs Connection with Postgresql

Asked

Viewed 682 times

0

I’m having trouble creating a module on nodejs to export my connection to PostgreSQL.

I couldn’t understand why according to code does not work as I would like to export connect.

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 it that 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 the connect, so I get the error that method query nay exists.

Because the second way, I can’t find the method query in my connection?

1 answer

2


In the second code you are already exporting the object that represents 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 just use:

var conexao = db;

  • Right. But if I export the connection already with the conect. When giving a require it will already be connected to the bank or only when assigned to a variable?

  • Yes, the connection occurs the moment you call the method .connect(). When you export the result of this call, you are exporting the connection and may reuse it elsewhere in the application (rather than connecting to the bank every time you need to perform a query).

  • And this way would be the best or not? Because if I am already connected with the bank could not be unfeasible?

  • 1

    Yes! Undoubtedly the best way is the second. Making connections all the time is an operation that takes time, your application can lose in performance.

  • Show thanks for the info. Just another thing I’m exporting a function in my module. Why can’t I use db() ? 'Cause from what I’ve learned I have to call it that when exported a function.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.