@anyme/anymejs
Version:
106 lines (102 loc) • 3.5 kB
JavaScript
'use strict';
var ioredis = require('ioredis');
var index = require('../utils/index.js');
class RedisManager {
logger;
redisMap = new Map();
constructor(config, logger) {
this.logger = logger;
this.init(config);
}
init(config) {
if (!config.enable || this.redisMap.size !== 0)
return;
if (!index.isEmpty(config.client))
this.set("default", config.client);
if (!index.isEmpty(config.clients))
Object.entries(config.clients).forEach(([key, opt]) => {
if ("default" in config && !index.isEmpty(config.default))
opt = index.deepMerge(config.default, opt);
this.set(key, opt);
});
}
createClient(opt) {
const defaultClient = this.redisMap.get("default");
const isClusterOpt = this.isClusterOpt(opt);
try {
if (!defaultClient)
return isClusterOpt
? new ioredis.Cluster(opt.node, opt.options)
: new ioredis.Redis(opt);
const isRedisClient = this.isRedis(defaultClient);
if (!isClusterOpt)
return isRedisClient ? defaultClient.duplicate(opt) : new ioredis.Redis(opt);
return !isRedisClient
? defaultClient.duplicate(opt.node, opt.options)
: new ioredis.Cluster(opt.node, opt.options);
}
catch (error) {
this.logger.error("❌ Failed to create redis client:", error);
return undefined;
}
}
set(key, opt) {
const client = this.createClient(opt);
if (client)
this.redisMap.set(key, client);
}
isRedis(client) {
return client instanceof ioredis.Redis;
}
isClusterOpt(opt) {
return "cluster" in opt && opt.cluster === true;
}
async connectAll() {
if (this.redisMap.size === 0)
return [];
return await index.all(this.redisMap, async ([key, client]) => {
if (client.status === "wait")
await this.connectClient(client, key);
return client.status;
});
}
async connectClient(client, key) {
try {
await client.connect();
this.logger.info(`✅ Redis client "${key}" connected successfully`);
}
catch (error) {
this.logger.error(`❌ Failed to connect Redis client "${key}":`, error);
throw error;
}
}
async close(name) {
const client = this.redisMap.get(name ?? "default");
if (!client)
return;
client.removeAllListeners();
await client.quit();
this.redisMap.delete(name ?? "default");
this.logger.debug(`✅ Redis connection closed: ${name}`);
}
get(name) {
const client = this.redisMap.get(name ?? "default");
if (!client)
throw new Error(`redis client "${name ?? "default"}" not found`);
return client;
}
getAll() {
return new Map(this.redisMap);
}
async closeAll() {
if (this.redisMap.size === 0)
return;
await index.all(this.redisMap, ([key, client]) => client
.removeAllListeners()
.quit()
.finally(() => this.redisMap.delete(key)), this);
this.logger.info("✅ All Redis connections closed");
}
}
exports.RedisManager = RedisManager;
//# sourceMappingURL=redis.js.map