I'm using node module "node-mssql" to connect a SQL Server.
I'm creating a bluebird promise and at the end this promise closes the connection. I did it because I don't know how to make a main connection, but I don't think opening/closing a connection each query is a good idea.
function connection() {
let promise = sql.connect('...');
promise.catch(function (err) {
console.log('********** Error on connecting **********');
console.log(err);
console.log('---------- Error on connecting ----------');
})
.finally(function () {
sql.close();
});
return promise;
};
var query = connection().then(function() {
new sql.Request()
.input('foo', mssql.NVarChar, 'bar')
.query('...')
.then(function (out) {
//...
})
.catch(function (err) {
console.log('********** Error on query **********');
console.log(err);
console.log('---------- Error on query----------');
});
});
Is there some way to have main connection?
Well... I solve this adding flags and functions, below my code, I hope it helps, or comment if there is a better way.
var mssql = require('mssql');
var sql = {}
sql.connected = false;
sql.connect = function () {
let promise = mssql.connect(SQL.String);
promise.catch(function (err) {
// handling error
mssql.close();
sql.connected = false;
});
return promise;
};
sql.Request = function () {
return new Promise(function (resolve, reject) {
if (!sql.connected) {
sql.connect()
.then(function () {
sql.connected = true;
resolve(new mssql.Request());
});
} else {
resolve(new mssql.Request());
}
});};