UNPKG

@boringnode/bus

Version:

A simple and lean driver-based service bus implementation

76 lines (75 loc) 2.09 kB
import { JsonEncoder } from "../../chunk-AY4GVNK4.js"; import { debug_default } from "../../chunk-ISFQ7A55.js"; // src/transports/redis.ts import { Redis } from "ioredis"; import { assert } from "@poppinss/utils/assert"; function redis(config, encoder) { return () => new RedisTransport(config, encoder); } var RedisTransport = class { #publisher; #subscriber; #encoder; #useMessageBuffer = false; #id; constructor(options, encoder) { this.#publisher = new Redis(options); this.#subscriber = new Redis(options); this.#encoder = encoder ?? new JsonEncoder(); if (typeof options === "object") { this.#useMessageBuffer = options.useMessageBuffer ?? false; } } setId(id) { this.#id = id; return this; } async disconnect() { await Promise.all([this.#publisher.quit(), this.#subscriber.quit()]); } async publish(channel, message) { assert(this.#id, "You must set an id before publishing a message"); const encoded = this.#encoder.encode({ payload: message, busId: this.#id }); await this.#publisher.publish(channel, encoded); } async subscribe(channel, handler) { this.#subscriber.subscribe(channel, (err) => { if (err) { throw err; } }); const event = this.#useMessageBuffer ? "messageBuffer" : "message"; this.#subscriber.on(event, (receivedChannel, message) => { receivedChannel = receivedChannel.toString(); if (channel !== receivedChannel) return; debug_default('received message for channel "%s"', channel); const data = this.#encoder.decode(message); if (data.busId === this.#id) { debug_default("ignoring message published by the same bus instance"); return; } handler(data.payload); }); } onReconnect(callback) { this.#subscriber.on("reconnecting", callback); } async unsubscribe(channel) { await this.#subscriber.unsubscribe(channel); } }; export { RedisTransport, redis }; /** * @boringnode/bus * * @license MIT * @copyright BoringNode */ //# sourceMappingURL=redis.js.map