All files / redis index.js

96.43% Statements 54/56
96.67% Branches 29/30
81.82% Functions 9/11
96.3% Lines 52/54

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 1151x 1x 1x 1x 1x     1x                                                         4x 1x   3x     7x 2x 2x   5x 5x 2x   3x 3x       1x 1x     1x 1x     4x 11x 4x     4x 4x 4x 4x 4x 2x 4x 4x 4x 3x 3x 2x           2x 1x       6x 5x 1x   4x 1x 1x 1x   4x 4x 4x   4x     4x       5x       1x
const Joi = require('joi');
const fs = require('fs');
const redis = require('redis');
const logger = require('@condor-labs/logger');
const { extractClientValue, removeIpPort } = require('../utils');
 
 
const self = {
    _settings: null,
    _client: undefined,
    _errorMsgInvalidSetting: 'INVALID_SETTINGS',
    _errorMsgUndefinedSetting: 'SETTINGS_NOT_DEFINED',
    _schema: Joi.object().keys({
        socket: Joi.object().keys({
            port: Joi.number().default(6379),
            host: Joi.string().default('127.0.0.1').required(),
            tls: Joi.boolean().default(false),
            key: Joi.string().when('tls', {
                is: true,
                then: Joi.string().required()
            }),
            ca: Joi.string().when('tls', {
                is: true,
                then: Joi.string().required()
            }),
            cert: Joi.string().when('tls', {
                is: true,
                then: Joi.string().required()
            })
        }).unknown(true),
        name: Joi.string().pattern(/\s/, { name: 'no space string', invert: true }).required(),
        password: Joi.string().default(null).allow(null).allow(''),
        prefix: Joi.string().default(null)
    }),
    _setSettings: settings => {
        //Validate the settings 
        if (!self._validateSettings(settings)) {
            throw new Error(self._errorMsgInvalidSetting);
        }
        self._settings = settings;
    },
    _validateSettings: settings => {
        if (!settings) {
            logger.error(self._errorMsgUndefinedSetting);
            return false;
        }
        const { error, value } = self._schema.validate(settings);
        if (error === void 0) {
            return true;
        } else {
            logger.error(`${error} - ${value}`);
            return false;
        }
    },
    _clientList: async () => {
        const list = await self._client.sendCommand(['CLIENT', 'LIST'])
        return list.split(`\n`)
    },
    _clientInfo: async () => {
        const info = await self._client.sendCommand(['CLIENT', 'INFO'])
        return info
    },
    _filterclient: async (name, addr) => {
        const list = await self._clientList()
        let clients = list.filter((client) => (client.includes(`addr=${addr}`) && (client.includes(`name=${name}`) || client.includes(`name= `))))
        return clients
    },
    _verifyUniqueConnection: async () => {
        const currenClient = await self._clientInfo()
        const actualID = extractClientValue('id', currenClient)
        const actualAddr = extractClientValue('addr', currenClient)
        const clients = await self._filterclient(self._settings.name, removeIpPort(actualAddr))
        if (clients.length > 1) {
            for (const client of clients) {
                const clientId = extractClientValue('id', client)
                const ageConnection = extractClientValue('age', client) || 0
                if (actualID !== clientId) {
                    const clientName = extractClientValue('name', client)
                    if (clientName === '' && Number(ageConnection) < 5) continue
                    const del = await self._killClient(clientId)
                }
            }
        }
    },
    _killClient: async (id) => {
        if (id) {
            return await self._client.clientKill({ filter: 'ID', id })
        }
    },
    getClient: async (forceReconnect = false) => {
        if (forceReconnect || !self._client) {
            if (!self._validateSettings(self._settings)) {
                throw new Error(self._errorMsgInvalidSetting);
            }
            if (self._settings.socket.tls === true) {
                self._settings.socket.key = fs.readFileSync(self._settings.socket.key, { 'encoding': 'ascii' })
                self._settings.socket.cert = fs.readFileSync(self._settings.socket.cert, { 'encoding': 'ascii' })
                self._settings.socket.ca = [fs.readFileSync(self._settings.socket.ca, { 'encoding': 'ascii' })]
            };
            self._client = await redis.createClient(self._settings);
            await self._client.connect()
            await self._verifyUniqueConnection();
 
            self._client.on("connect", async () => {
                logger.info(`connecting redis`);
            });
            self._client.on("error", (err) => {
                logger.error(`Error ocurred connecting to Redis <br/> Stack: ${err}`);
            });
        }
        return self._client;
    }
};
 
module.exports = self;