-
Notifications
You must be signed in to change notification settings - Fork 0
/
dbContext.js
50 lines (40 loc) · 1.35 KB
/
dbContext.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
const sql = require('mssql/msnodesqlv8');
const dbConfig = require('./dbConfig');
let connPoolPromise = null;
const getConnPoolPromise = () => {
// If the connection pool exists, return it...
if (connPoolPromise) {
return connPoolPromise;
}
// Create the connection pool...
connPoolPromise = new Promise((resolve, reject) => {
// Initialize the connection pool with the dbConfig...
const conn = new sql.ConnectionPool(dbConfig);
// When the connection pool is closed, set the
// object to null...
conn.on('close', () => connPoolPromise = null);
// Connect to the database...
conn.connect()
.then(connPool => resolve(connPool))
.catch(err => {
connPoolPromise = null;
return reject(err);
});
});
return connPoolPromise;
};
const query = (sqlQuery, callback) => {
if (!callback) {
console.log('dbContext callback function is not defined!');
return;
}
if (!sqlQuery) {
callback(new Error('SQL statement is a required parameter.'));
}
getConnPoolPromise()
.then(connPool => connPool.request().query(sqlQuery))
.then(result => callback(null, result))
.catch(err => callback(err));
};
// Fetch data using callback...
module.exports = { query: query };