Skip to content

Instantly share code, notes, and snippets.

@NathBabs
Last active January 25, 2023 15:53
Show Gist options
  • Save NathBabs/e8e992f50ecdba96a05d2bc435ab0f0f to your computer and use it in GitHub Desktop.
Save NathBabs/e8e992f50ecdba96a05d2bc435ab0f0f to your computer and use it in GitHub Desktop.
Connecting to Redis
const fetchKeys = (obj, keys) => {
const filteredObject = {};
if (Array.isArray(keys)) {
keys.forEach((key) => {
// eslint-disable-next-line no-prototype-builtins
if (obj.hasOwnProperty(key)) {
filteredObject[key] = obj[key];
}
});
} else if (typeof keys === "string") {
// eslint-disable-next-line no-prototype-builtins
if (obj.hasOwnProperty(keys)) {
filteredObject[keys] = obj[keys];
}
}
return filteredObject;
};
import bluebird from "bluebird";
import redis from "redis";
import logger from "./logger";
bluebird.promisifyAll(redis.RedisClient.prototype);
bluebird.promisifyAll(redis.Multi.prototype);
let client = null;
const RedisClient = () => {
try {
if (!client) {
client = redis.createClient({
host: process.env.REDIS_HOST,
port: process.env.REDIS_PORT,
password: process.env.REDIS_PASS,
retry_strategy: (options) => {
if (options.error && options.error.code === "ECONNREFUSED") {
// End reconnecting if there is any specific error
return new Error("The server refused the connection");
}
if (options.total_retry_time > 1000 * 60 * 5) {
// End reconnecting after 5 minues and flush all commands with a individual error
return new Error("Retry time exhausted");
}
if (options.attempt > 10) {
// End reconnecting with built in error
return undefined;
}
// reconnect after
return Math.min(options.attempt * 100, 3000);
},
});
}
return client;
} catch (e) {
logger.error("::: failed to connect to redis :::");
return null;
}
};
export default { getInstance: RedisClient };
redisclientStub = sinon.stub(RedisClient, 'getInstance').returns({
getAsync: sinon.stub().resolves(JSON.stringify(userDetails)),
setAsync: sinon.stub().resolves(true),
expireAsync: sinon.stub().resolves(true),
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment