Skip to content

Instantly share code, notes, and snippets.

@akama-aka
Created March 3, 2025 09:55
Database Connector for pg for NodeJS Projects
const { Pool } = require("pg");
const pool = new Pool({
host: process.env.DB_HOST,
user: process.env.DB_USERNAME,
password: process.env.DB_PASSWORD,
database: process.env.DB_NAME,
port: process.env.DB_PORT,
max: 20,
idleTimeoutMillis: 30000,
connectionTimeoutMillis: 2000,
native: true,
});
function dbConnect() {
pool.connect(async function (err, release) {
//await log(2, "Connected to the Database", "Server", "info");
if (err) {
console.error("Database Connection Failed. Retrying in 5 seconds...");
setInterval(() => {
dbConnect();
}, 5000);
} else {
console.log("Connected to the Database");
}
});
}
dbConnect();
/**
* @desc Query the Database
* @param {string} query
* @param {Array} params
* @returns {Promise<QueryArrayResult<any[]>>}
*/
async function query(query, params = null) {
const data = await pool.query(query, params);
return data;
}
/**
* @desc Query the Database
* @param {string} text - The Query to be executed
* @param {Array} params - The Parameters for the Query
* @returns {Promise<QueryArrayResult<any[]>>}
* @type {{query: (function(*, *): Promise<QueryArrayResult<any[]>>), release: (function(): *)}}
*/
module.exports = {
query,
/**
* @desc Release the Connection
* @returns {Promise<void>}
*/
release: () => pool.end(),
/**
* @desc Connect to the Database
* @returns {Promise<PoolClient>}
*/
connect: () => pool.connect(),
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment