skip to Main Content

I have the following module which connects to a Redis database, and I want to get the client instance so I can call it from other modules without creating a new instance each time, I did the following:

let client;

const setClient = ({ redis, config }) => {
    client = redis.createClient({
        host: config.redis.host,
        port: config.redis.port
    });
};

const getClient = () => {
    return client;
};

const connect = ({ redis, config, logger }) => {
    setClient({ redis, config });
    client.on('connect', () => {
        logger.info(`Redis connected on port: ${client?.options?.port}`);
    });
    client.on('error', err => {
        logger.error(`500 - Could not connect to Redis: ${err}`);
    });
};

module.exports = { connect, client: getClient() };

when i call the client from other modules using const { client } = require('./cache'); it gives me undefined

2

Answers


  1. Chosen as BEST ANSWER

    I come up with the following solution:

    const cacheClient = () => {
        return {
            client: undefined,
            setClient({ redis, config }) {
                client = redis.createClient({
                    host: config.redis.host,
                    port: config.redis.port
                });
            },
    
            getClient() {
                return client;
            },
    
            connect({ redis, config, logger }) {
                this.setClient({ redis, config });
                client.on('connect', () => {
                    logger.info(`Redis connected on port: ${client?.options?.port}`);
                });
                client.on('error', err => {
                    logger.error(`500 - Could not connect to Redis: ${err}`);
                });
            }
        };
    };
    
    module.exports = cacheClient;
    

    If there's a better approach please let me know.


  2. erase letClient() from top(the let) and on the bottom add const client = getClient() and on module exports just go with client instead of client: getClient()

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search