I can't understand how to connect PostgreSQL pool in NodeJS and do it correctly. I am using Express with Router, all handlers are placed in different files. Everyone advises to make a separate file with a DB connection and then "require" it in each source code file. Is it possible to connect this pool through app.use or something else? All my handlers always use DB connection, for each user request.
Asked
Active
Viewed 5,430 times
3
-
This should help: http://mherman.org/blog/2016/03/13/designing-a-restful-api-with-node-and-postgres/ – vitaly-t May 08 '17 at 23:40
-
@vitaly-t did you read my question? I'm asking about other solutions. This solution is bad and not recommended to using in real-life – Alexey Rodionov May 09 '17 at 15:51
-
Your description of the problem is too vague, impossible to understand what the nature of the problem is. Plus the question's title is misleading. I would suggest to re-think your question and ask it more to the point ;) – vitaly-t May 09 '17 at 16:01
1 Answers
7
I'm pretty sure the example below is what others are telling you to do, this utilizes the postgres' pooling.
If there's another method that would be as simple as a require and technically 2 loc per file, I'd love to hear it.
Example of a required querydb file:
"use strict";
const pg = require('pg');
const config = {
connectionString: 'postgres://username:password@server/database'
};
const pool = new pg.Pool(config);
const DB = {
query: function(query, callback) {
pool.connect((err, client, done) => {
if(err) return callback(err)
client.query(query, (err, results) => {
done()
if(err) { console.error("ERROR: ", err) }
if(err) { return callback(err) }
callback(null, results.rows)
})
});
}
}
Then anywhere when you want to query the database you just use the few lines below instead of copy/pasting the entire connection pooling method.
Example usage
const queryDB = require("../queryDB.js");
...
let query = "SELECT * FROM table;"
queryDB.query(query, (err, results) => {
// Handle err/results
})

Eduardo Vazquez
- 2,454
- 1
- 12
- 8

C Jones
- 231
- 1
- 3
-
Hi, How to release the connection after each query execution? Like suppose I have 10 queries running then after 1st query how to release the connection with above code? – Akash M Apr 10 '21 at 07:21