@eventstore.net/event.store
Version:
A simple and fast EventStore that support multiple persistence and notification providers
49 lines • 1.87 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
const connect_1 = require("../redis/connect");
/**
* A Publisher that use Redis pub / sub feature to message communications.
*/
class RedisPublisher {
constructor(config) {
this.listeners = new Map();
this.listenningRedis = false;
this.redisSubscriber = connect_1.RedisFactory.createClient(config);
this.redisPublisher = connect_1.RedisFactory.createClient(config);
}
async publish(message) {
const listeners = await this.redisPublisher.publish(message.stream.aggregation, JSON.stringify(message));
return listeners > 0;
}
async subscribe(aggregation, subscriber) {
let subscribers = this.listeners.get(aggregation);
if (!subscribers) {
subscribers = new Array();
this.listeners.set(aggregation, subscribers);
}
subscribers.push(subscriber);
await this.redisSubscriber.subscribe(aggregation);
await this.registerRedisListener();
return {
remove: async () => {
const index = subscribers.indexOf(subscriber);
subscribers.splice(index, 1);
if (subscribers.length === 0) {
this.redisSubscriber.unsubscribe(aggregation);
}
}
};
}
async registerRedisListener() {
if (!this.listenningRedis) {
this.listenningRedis = true;
await this.redisSubscriber.on('message', (aggregation, received) => {
const message = JSON.parse(received);
const subscribers = this.listeners.get(aggregation);
subscribers.forEach(subscriber => subscriber(message));
});
}
}
}
exports.RedisPublisher = RedisPublisher;
//# sourceMappingURL=redis.js.map