Last active
December 16, 2015 09:28
-
-
Save wwwy3y3/5412976 to your computer and use it in GitHub Desktop.
async database connection manager, singleton pattern
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
var path= require('path'); | |
//var cpath= path.resolve(__dirname, '..', '..', '..', 'node_modules', 'cassandra-client'); | |
var Connection = require('cassandra-client').Connection; | |
var EventEmitter = require('events').EventEmitter; | |
/* | |
* four stages of connection | |
* 1. restart the server, connection is null | |
* 2. new Connection(options), but not yet connect, (client= null, doesn't have con, nothing in validators) | |
************************* | |
{ validators: {}, | |
client: null, | |
connectionInfo: { host: '127.0.0.1', port: 9160, keyspace: 'clubond_1_1' }, | |
timeout: 4000, | |
query_timeout: 5000, | |
cql_version: undefined, | |
_id: 1, | |
_pendingQueryCallbacks: {}, | |
_queryIdCounter: 0, | |
domain: | |
{ domain: null, | |
_events: { error: [Function] }, | |
_maxListeners: 10, | |
members: [ [Object], [Object] ] }, | |
_events: null, | |
_maxListeners: 10 } | |
************************** | |
* | |
* connect will add `con` and `client` | |
* 3. connnect not yet callback, still connecting!!!!, connection.con.connected is false | |
* 4. connected after login learn use, connection.con.connected is true | |
* | |
* | |
*/ | |
var connection = null; | |
//first stage- connection is null | |
var conManager= new EventEmitter(); | |
module.exports = function (_options, callback){ | |
var options = _options; | |
if(connection && typeof connection.con !== 'undefined' && connection.con.connected) | |
return callback(null, connection); | |
//stage 2- wait for connection | |
if(connection && typeof connection.con !== 'undefined' && !connection.con.connected){ | |
conManager.on('connected', function (con) { | |
callback(null, con); | |
}) | |
conManager.on('error', function (err) { | |
callback(err); | |
}) | |
return; | |
} | |
//stage 1- connection is null- create a conneciton | |
if(!connection){ | |
conManager.on('connected', function (con) { | |
callback(null, connection); | |
}) | |
conManager.on('error', function (err) { | |
callback(err); | |
}) | |
connection= new Connection(options); | |
connection.connect(function(err) { | |
if (err) | |
return conManager.emit('error', err); | |
return conManager.emit('connected', connection); | |
}); | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment