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
I come up with the following solution:
If there's a better approach please let me know.
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()