redis-smq-common
Version:
Provides essential components and utilities shared across RedisSMQ packages.
119 lines • 4 kB
JavaScript
import { CallbackEmptyReplyError, PanicError } from '../errors/index.js';
import { EventEmitter } from '../event/index.js';
import { InstanceLockError } from './errors/index.js';
import { ERedisConfigClient, } from './types/index.js';
import { UnsupportedClientError, RedisClientNotInstalledError, } from './errors/index.js';
export class RedisClientFactory extends EventEmitter {
instance = null;
locked = false;
config;
constructor(config) {
super();
this.config = config;
}
createClient(config, cb) {
this.createRedisClient(config, (err, client) => {
if (err)
return cb(err);
if (!client)
return cb(new CallbackEmptyReplyError());
this.setupClient(client, cb);
});
}
setupClient(client, cb) {
cb(null, client);
}
init = (cb) => {
this.getSetInstance((err) => cb(err));
};
getSetInstance = (cb) => {
if (!this.locked) {
if (!this.instance) {
this.locked = true;
this.createClient(this.config, (err, client) => {
this.locked = false;
if (err)
return cb(err);
if (!client)
return cb(new CallbackEmptyReplyError());
this.instance = client;
this.instance.on('error', (err) => this.emit('error', err));
cb(null, this.instance);
});
}
else
cb(null, this.instance);
}
else
cb(new InstanceLockError());
};
shutdown = (cb) => {
if (this.instance) {
this.instance.halt(() => {
this.instance = null;
cb();
});
}
else
cb();
};
getInstance() {
if (!this.instance)
throw new PanicError({
message: 'Use first init() to initialize the RedisClientInstance class',
});
return this.instance;
}
createNodeRedisClient(config, cb) {
import('./clients/node-redis/node-redis-client.js')
.then(({ NodeRedisClient }) => {
const client = new NodeRedisClient(config.options);
cb(null, client);
})
.catch(() => cb(new RedisClientNotInstalledError({
metadata: { clientId: '@redis/client' },
})));
}
createIORedisClient(config, cb) {
import('./clients/ioredis/ioredis-client.js')
.then(({ IoredisClient }) => {
const client = new IoredisClient(config.options);
cb(null, client);
})
.catch(() => cb(new RedisClientNotInstalledError({
metadata: { clientId: 'ioredis' },
})));
}
initializeRedisClient(config, cb) {
if (config.client === ERedisConfigClient.REDIS) {
return this.createNodeRedisClient(config, cb);
}
if (config.client === ERedisConfigClient.IOREDIS) {
return this.createIORedisClient(config, cb);
}
cb(new UnsupportedClientError());
}
createRedisClient(config, cb) {
this.initializeRedisClient(config, (err, client) => {
if (err)
return cb(err);
if (!client)
return cb(new CallbackEmptyReplyError());
const onReady = () => {
removeListeners();
cb(null, client);
};
const onError = (err) => {
removeListeners();
cb(err);
};
const removeListeners = () => {
client.removeListener('ready', onReady);
client.removeListener('error', onError);
};
client.once('ready', onReady);
client.once('error', onError);
});
}
}
//# sourceMappingURL=redis-client-factory.js.map