использовать экземпляр клиента Redis в других модулях в NodeJS

#javascript #node.js #redis #commonjs

#javascript #node.js #redis #commonjs

Вопрос:

У меня есть следующий модуль, который подключается к базе данных Redis, и я хочу получить экземпляр клиента, чтобы я мог вызывать его из других модулей, не создавая каждый раз новый экземпляр, я сделал следующее:

 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() };
 

когда я вызываю клиента из других модулей, используя const { client } = require('./cache'); его, я undefined

Ответ №1:

удалите letClient() сверху (let) и внизу добавьте const client = getClient(), а при экспорте модуля просто используйте client вместо client: getClient()

Комментарии:

1. Не удается получить доступ к «клиенту» перед инициализацией. Пожалуйста, не могли бы вы предоставить фрагмент кода?

Ответ №2:

Я пришел к следующему решению:

 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;
 

Если есть лучший подход, пожалуйста, дайте мне знать.