Created
January 28, 2015 21:46
-
-
Save tracker1/5ad0bff295369ac05eea to your computer and use it in GitHub Desktop.
get-mssql-connection.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//get-connection.js | |
'use strict'; | |
require('promisify-patch').patch(); | |
var _ = require('lodash') | |
,cfg = require('./config') | |
,sql = require('mssql') | |
,Promise = require('i-promise') | |
,pools = {} | |
; | |
module.exports = getConnection; | |
//TODO: replace name with cfg, and use a composite of server/user/database for pools... | |
function getConnection(name) { | |
//if not a valid config name - reject | |
if (!cfg.sql[name]) return Promise.reject(new Error('The specified connection does not exist.')); | |
//already a promise for the connection - return it | |
if (pools[name]) return pools[name]; | |
//return and generate a promise for the connection | |
return pools[name] = new Promise(function(resolve, reject){ | |
var conn = new sql.Connection(cfg.sql[name], function(err){ | |
if (err) { | |
delete pools[name]; //not connected | |
return reject(err); | |
} | |
return resolve(conn); | |
}) | |
}); | |
} | |
getConnection.close = function closeConnection(name){ | |
if (!pools[name]) return; | |
var cp = pools[name]; | |
delete pools[name]; | |
cp.then(function(conn){ | |
conn.close(); | |
}); | |
}; | |
getConnection.closeAll = function closeAllConnections(){ | |
_.each(_.keys(pools),getConnection.close); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment