UNPKG

@boringnode/bus

Version:

A simple and lean driver-based service bus implementation

89 lines (88 loc) 2.45 kB
import { JsonEncoder, tryDecodeTransportMessage } from "../../chunk-DZUPXJD3.js"; import { debug_default } from "../../chunk-6ST7Q25E.js"; import "../../chunk-66RTAHC7.js"; // src/transports/mqtt.ts import { connect } from "mqtt"; import { assert } from "@poppinss/utils/assert"; function mqtt(config, encoder) { return () => new MqttTransport(config, encoder); } var MqttTransport = class { #id; #client; #url; #encoder; #handlers = /* @__PURE__ */ new Map(); constructor(config, encoder) { this.#encoder = encoder ?? new JsonEncoder(); this.#url = `${config.protocol || "mqtt" /* MQTT */}://${config.host}${config.port ? `:${config.port}` : ""}`; this.#client = connect(this.#url, config.options ?? {}); this.#client.on("message", this.#onMessage); } setId(id) { this.#id = id; return this; } async disconnect() { await this.#client.endAsync(); } 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.#client.publishAsync(channel, encoded); } async subscribe(channel, handler) { const handlers = this.#handlers.get(channel) ?? []; handlers.push(handler); this.#handlers.set(channel, handlers); try { await this.#client.subscribeAsync(channel); } catch (error) { handlers.splice(handlers.indexOf(handler), 1); if (handlers.length === 0) { this.#handlers.delete(channel); } throw error; } } onReconnect() { this.#client.reconnect(); } async unsubscribe(channel) { await this.#client.unsubscribeAsync(channel); this.#handlers.delete(channel); } #onMessage = (channel, message) => { const handlers = this.#handlers.get(channel); if (!handlers) return; debug_default('received message for channel "%s"', channel); const data = tryDecodeTransportMessage(this.#encoder, message); if (!data) { debug_default('ignoring invalid message for channel "%s"', channel); return; } if (data.busId === this.#id) { debug_default("ignoring message published by the same bus instance"); return; } for (const handler of handlers) { handler(data.payload); } }; }; export { MqttTransport, mqtt }; /** * @boringnode/bus * * @license MIT * @copyright BoringNode */ //# sourceMappingURL=mqtt.js.map