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 methodquery
nay exists.
Because the second way, I can’t find the method query
in my connection?
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?
– Aprendiz
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).– Ruan Martinelli
And this way would be the best or not? Because if I am already connected with the bank could not be unfeasible?
– Aprendiz
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.
– Ruan Martinelli
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.
– Aprendiz