@allgemein/eventbus
Version:
100 lines • 3.07 kB
JavaScript
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.AbstractRedisConnection = void 0;
const events_1 = require("events");
const redis_1 = require("redis");
const lodash_1 = require("lodash");
class AbstractRedisConnection extends events_1.EventEmitter {
constructor(options) {
super();
this.inc = 0;
this.ready = false;
this.errored = false;
this.options = options;
}
isOpened() {
return this.ready;
}
async getClient(connect = true) {
if (!this.client) {
if (connect) {
this.client = (await this.connect());
}
else {
throw new Error('No redis client found.');
}
}
return this.client;
}
async connect() {
if (this.ready) {
return Promise.resolve(this.client);
}
this.ready = false;
let url = this.options.url;
if (!url) {
// redis://alice:foobared@awesome.redis.server:6380
let host = '';
if (this.options.host) {
host += this.options.host;
}
else {
host += 'localhost';
}
if (this.options.port) {
host += ':' + this.options.port;
}
else {
host += ':6379';
}
let user = '';
if (this.options.username && this.options.password) {
user += this.options.username + ':' + this.options.password;
}
if (user) {
url = 'redis://' + user + '@' + host;
}
else {
url = 'redis://' + host;
}
this.options.url = url;
}
// console.log(this.constructor.name + ' connect ' + this.inc + ' ' + this.options.url);
const client = (0, redis_1.createClient)(this.options);
try {
await client.connect();
this.ready = true;
if ((0, lodash_1.get)(this.options, 'unref', false)) {
client.unref();
}
// console.log(this.constructor.name + ' connected ' + this.inc + ' ' + this.options.url);
}
catch (err) {
this.ready = false;
if (this.client) {
this.client.removeAllListeners();
this.client = null;
}
err.message = err.message + ' (#onError ' + this.constructor.name + ')';
throw err;
}
return client;
}
async quit() {
if (!this.ready) {
return Promise.resolve();
}
if (!this.client) {
return Promise.resolve();
}
this.ready = false;
const c = this.client;
await c.quit();
if (c) {
c.removeAllListeners();
this.client = null;
}
}
}
exports.AbstractRedisConnection = AbstractRedisConnection;
//# sourceMappingURL=AbstractRedisConnection.js.map