I'm new to node and the async paradigm, so maybe I'm thinking about this wrong.
Anyway, what I'm trying to do is create a generic module for connecting using tedious-connection-pool. Here is the code for the sqlConnection.js module:
var ConnectionPool = require("tedious-connection-pool");
var baseConfig = {
userName: 'username',
password: 'password',
server: 'server'
};
var poolConfig = {
max: 10,
min: 0,
idleTimeoutMillis: 30000
};
function createConfig(config, options) {
config.options = options;
return config;
}
function executeStatement(connection, request) {
connection.execSql(request);
}
function connectAndExecute(configOptions, request) {
var pool = new ConnectionPool(poolConfig, createConfig(baseConfig, configOptions));
pool.requestConnection(function (err, connection) {
if(!err) {
console.log("Executing: " + request);
} else {
console.log("Could not create pool connection");
}
connection.on('connect', function(err) {
if(err) {
console.log('Connection Error: ' + err);
return;
} else {
executeStatement(connection, request);
}
});
});
}
exports.connectAndExecute = connectAndExecute;
//end of module
If I can do something like this, then I can just define what database to connect to passing in the database specific options and I can define Requests in their individual files and then pass them to the generic connection module to execute. The problem that I have is that the callback for a Request is the only place where I can be sure that the query has been run and close the connection. Like this:
var Request = require("tedious").Request;
var sqlConnection = require('./sqlConnection');
var options = {
database: 'database',
rowCollectionOnRequestCompletion: true
};
var request = new Request("delete from dbo.Table", function(err, rowCount, rows) {
if (err) {
console.log(err);
} else {
console.log("Table cleared");
}
connection.close();
});
sqlConnection.connectAndExecute(options, request);
//end of file
The problem is that connection is not defined in this scope - so I can't do this.
But I shouldn't need to copy and paste the connection code every time I want to run a query (Don't Repeat Yourself).
Is this a problem in the async paradigm, the way the library is set up or am I just going about it wrong?