all files / src/utils/ redis-subscriber.js

80% Statements 28/35
50% Branches 4/8
100% Functions 3/3
80% Lines 28/35
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79                                                                                      182×     182× 182×            
/**
 * @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;