spice-cache-redis
Version:
spice redis cache provider
87 lines (78 loc) • 2.77 kB
JavaScript
let redis = require("redis");
const retry = require("retry");
const createClient = redis.createClient;
module.exports = class SpiceRedisCache {
constructor(args = {}) {
this.options = args;
this.client = null;
}
async initialize(options = {}) {
this.options = { ...this.options, ...options };
return new Promise((resolve, reject) => {
this.client = createClient({
url: `${this.options?.use_tls ? "rediss" : "redis"}://${
this.options.username || "default"
}:${this.options.password || ""}@${
this.options.server || "localhost"
}:${this.options.port || 6379}`,
retry_strategy: function (opts) {
console.log("Retrying...", opts);
if (opts.error && opts.error.code === "ECONNREFUSED") {
console.log("The server refused the connection");
return new Error("The server refused the connection");
}
if (opts.total_retry_time > 1000 * 60 * 60) {
return new Error("Retry time exhausted");
}
if (opts.attempt > (this.options.max_retries || 10)) {
return undefined; // Stop reconnecting after the max number of retries
}
return Math.min(
opts.attempt * (this.options.retry_factor || 100),
this.options.max_retry_delay || 3000
);
}.bind(this),
});
this.client.connect();
this.client.on("connect", () => {
console.log("Redis client is attempting to connect");
});
this.client.on("end", () => {
console.log("Redis connection closed");
});
this.client.on("error", (err) => {
console.log("Redis error: " + err);
this.client.quit();
reject(err); // Reject the promise on an error
});
this.client.on("ready", () => {
console.log("Redis is ready");
resolve(); // Resolve the promise when the client is ready
});
});
}
async set(key, value, options = {}) {
if (this.client.isReady) {
let working_options = { ...this.options, ...options };
const { ttl, namespace = "" } = working_options;
if (value === undefined) return console.log("Value is undefined");
await this.client.set(namespace + key, JSON.stringify(value));
await this.client.expire(namespace + key, ttl || 900000);
}
}
async get(key, options = {}) {
try {
let working_options = { ...this.options, ...options };
const { namespace = "" } = working_options;
if (this.client.isReady) {
return JSON.parse(await this.client.get(namespace + key));
}
return;
} catch (e) {
return null;
}
}
async exists(key) {
return await this.client.exists(key);
}
};