I am reading the documentation and trying to figure out connection pooling.
The documentation says that the pool should be long lived, so I have created a config/db.js file where I create pool and export it:
/* src/config/db.js */
const pg = require('pg');
const dbConfig = {
host: process.env.DB_HOST,
port: process.env.DB_PORT,
user: process.env.DB_USER,
password: process.env.DB_PASS,
database: process.env.DB_DATABASE,
max: 25,
idleTimeoutMillis: 5000
};
const pool = new pg.Pool(dbConfig);
module.exports = {
pool
};
I have a bunch of routes and controllers. For example, I have /markers endpoint which has a few methods in the controller. In the controller file, I am importing pool from the config/db.js and using it. Is that OK?
const pool = require('../config/db').pool;
const create = function (req, res, next) {
const data = {
created_by: req.body.createdBy,
title: req.body.title,
description: req.body.description,
lat: req.body.lat,
lng: req.body.lng
};
pool.connect((err, client, done) => {
if (err) {
done();
// console.log(err);
return res.status(500).json({ success: false, data: err });
}
client.query(
'INSERT INTO markers(created_by, title, description, lat, lng, geography)\
values($1, $2, $3, $4::decimal, $5::decimal, ST_SetSRID(ST_MakePoint($5::decimal, $4::decimal), $6))',
[
data.created_by,
data.title,
data.description,
data.lat,
data.lng,
4326
],
function(err, res) {
done();
if (err) {
// console.log(err);
}
}
);
return res.status(200).json({ success: true });
});
};
Also, how do I check that the insert was successful so that I don't just return a 200 success if there's no error without knowing if the insert was successful?