Express application allows to open only one database connection pool object across the application.
In this example,
1/ mssql library is used to connect MS-SQL server
2/ one time connection pool is generated in the library file "commonDbConnection.js"
3/ above library is referred where ever its required. In our example, used it in "server.js" & "anotherlibraryfile.js"
config.js
var config = {
databaseConn: {
server: "dbserver",
database: "db",
user: "uid",
password: "pwd",
options: {
encrypt: false
}
},
Config_Key1: 'config_value1',
Config_Key2: 'config_value2',
Config_Obj: {
config_key3 : 'config_value3',
config_key4 : 'config_value4',
config_key5 : 'config_value5',
}
};
module.exports = config ;
commonDbConnection.js
It returns as a promise object "commonConnPool"
var config = require("./config").databaseConn;
const mssql = require("mssql");
const commonConnPool = new mssql.ConnectionPool(config)
.connect()
.then(pool => {
console.log("Connected to MSSQL");
return pool;
})
.catch(err => console.log("Database Connection Failed! Bad Config: ", err));
module.exports = {
mssql,
commonConnPool
};
server.js
....
var commonConnPool= require('./commonDbConnection').commonConnPool;
(or)
var {commonConnPool} = require('./commonDbConnection')
....
//While setup CORS inject the DB connection pool and later you can retrieve it in the API library
app.use(async function (req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
req.conn_pool = await commonConnectionPool;
next();
});
...
app.use('/api', api);
anotherlibraryfile.js
var { commonConnPool, mssql } = require('./dbInitCommonConn');
async insertIntoDB(value1, value2, value3) {
try {
await commonConnPool.then(pool => {
pool
.request()
.input("param1", mssql.VarChar(50), value1)
.input("param2", mssql.VarChar(50), value2)
.input("param3", mssql.VarChar(50), JSON.stringify(value3)) //if its object, then stringify it before pass
JSON.stringify(message)
)
.execute("usp_Insert_Record_SP");
});
} catch (err) {
console.log("error occurred", err);
}
}