File: //var/dev/farhangmoaser/web/connectors/redis.js
/**
* Redis Connector
* Version: 0.1
* Author: Babak Vandad
*
* Manages a singleton connection to MySQL
*/
var redis = require('redis');
var config = require('../config.js');
var client;
/**
* Attempts to connect to Redis.
* @param {Function} callback Callback function
*/
function connect(callback) {
var host = config.read('redis.host') || 'localhost';
var port = config.read('redis.port') || 6379;
if(config.read('redis.username'))
client = redis.createClient(`redis:\/\/${config.read('redis.username')}:${config.read('redis.password')}@${host}:${port}`);
else
client = redis.createClient(port, host);
client.on('connect', function(){
// console.log('redis db connected.');
if(callback)
callback(client);
});
client.on('errpr', function(){
console.log('redis db error.');
});
}
/**
* If a connection request has been issued, returns the client object.
* Otherwise connects to the db.
* IMPORTANT: If there is an ongoing attemp, it returns the client object, which does not have a stablished connection yet.
* @param {Function} callback Callback function
*/
exports.connect = function(callback){
if(client){
if(callback)
process.nextTick(function (){
callback(client);
});
}
else
connect(callback);
};
exports.connectPromise = function(){
return new Promise((resolve, reject) => {
if(client)
process.nextTick(() => resolve(client));
else
connect(resolve);
});
};
/**
* Returns current mysql object synchronously whether connected or not.
* @return {Object} MySQL connection object
*/
exports.client = function() {
return client;
};