redikit
Version:
TypeScript version of lightweight Redis utility functions for caching and pub/sub
55 lines (54 loc) • 2.49 kB
JavaScript
;
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", { value: true });
const redis_1 = require("redis");
class RedisPubSub {
static connect() {
return __awaiter(this, void 0, void 0, function* () {
if (this.connected)
return;
this.publisher = (0, redis_1.createClient)();
this.subscriber = (0, redis_1.createClient)();
this.publisher.on('error', (err) => console.error('Publisher Error:', err));
this.subscriber.on('error', (err) => console.error('Subscriber Error:', err));
yield Promise.all([this.publisher.connect(), this.subscriber.connect()]);
this.connected = true;
});
}
static publish(channel, message) {
return __awaiter(this, void 0, void 0, function* () {
yield this.connect();
if (!this.publisher)
throw new Error('Publisher client not initialized');
yield this.publisher.publish(channel, JSON.stringify(message));
});
}
static subscribe(channel, callback) {
return __awaiter(this, void 0, void 0, function* () {
yield this.connect();
if (!this.subscriber)
throw new Error('Subscriber client not initialized');
// Redis v4 subscribe returns a Promise resolving once subscription starts
yield this.subscriber.subscribe(channel, (message) => {
try {
callback(JSON.parse(message));
}
catch (_a) {
callback(message); // fallback in case JSON parsing fails
}
});
});
}
}
RedisPubSub.publisher = null;
RedisPubSub.subscriber = null;
RedisPubSub.connected = false;
exports.default = RedisPubSub;