@boringnode/bus
Version:
A simple and lean driver-based service bus implementation
71 lines (70 loc) • 1.86 kB
JavaScript
import {
JsonEncoder
} from "../../chunk-AY4GVNK4.js";
import {
debug_default
} from "../../chunk-ISFQ7A55.js";
import "../../chunk-ITP7PBIY.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;
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 ?? {});
}
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) {
this.#client.subscribe(channel, (err) => {
if (err) {
throw err;
}
});
this.#client.on("message", (receivedChannel, message) => {
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() {
this.#client.reconnect();
}
async unsubscribe(channel) {
await this.#client.unsubscribeAsync(channel);
}
};
export {
MqttTransport,
mqtt
};
/**
* @boringnode/bus
*
* @license MIT
* @copyright BoringNode
*/
//# sourceMappingURL=mqtt.js.map