/**
* @file redis-subcriber
* @desc Redis subscriber mode connection helper
*
*/
'use strict';
const _ = require('lodash');
const config = require(__dirname + '/../config');
const EventEmitter = require('events').EventEmitter;
const redis = require('redis');
const logger = require(__dirname + '/../loggers/logger');
class RedisSubcriber extends EventEmitter {
/**
* @constructor
*
* @desc Initialize the redis connection in subscriber mode
*
*/
constructor() {
super();
this.ready = false;
this.redisClient = redis.createClient(config.networking.redis_port,
config.networking.local_redis_host);
this.channel = config.pnr_enforcement.redis_logging_channel;
Eif (config.networking.redis_password) {
this.redisClient.auth(config.networking.redis_password, (err) => {
Iif (err) {
logger.error('Redis Auth Error - "' + err + '"');
} else {
logger.info('Redis Auth succeeded');
}
});
}
this.redisClient.on('ready', () => {
// Duplicate connnection that allows redis status commands
this.redisPubClient = this.redisClient.duplicate(
this.redisClient.options);
Eif (!_.isEmpty(this.redisClient.auth_pass)) {
this.redisPubClient.auth(this.redisClient.auth_pass);
}
this.subscribe();
});
this.redisClient.on('error', (err) => {
this.ready = false;
logger.error('Redis Error - "' + err + '"');
});
this.redisClient.on('end', () => {
this.ready = false;
logger.error('Redis subscriber mode connection terminated');
});
}
subscribe() {
logger.info('Subscribing to channel: "' + this.channel + '"');
this.redisClient.subscribe(this.channel);
this.ready = true;
this.redisClient.on('message', (channel, message) => {
this.emit('message', channel, message);
});
}
getStatus(cb) {
Iif (!this.ready) {
return cb('Unavailable');
}
this.redisPubClient.pubsub('numsub', this.channel, (err, res) => {
return cb(err, res);
});
}
}
// export the RedisSubcriber class
module.exports = RedisSubcriber;
|