diff --git a/src/nats.ts b/src/nats.ts index ce93e28..08bb72e 100644 --- a/src/nats.ts +++ b/src/nats.ts @@ -1,6 +1,8 @@ import { connect, JSONCodec } from "nats"; import type { ConnectionOptions, NatsConnection, Payload } from "nats"; import { log } from "./logger"; +import { hostname } from "node:os"; +import type { MQFileUpdate } from "@owlboard/backend-data-contracts/dist/data-ingress_mq-file-update"; const jc = JSONCodec(); @@ -9,7 +11,7 @@ async function getNatsConnection(): Promise { const options: ConnectionOptions = { servers: serverUrl, - name: `${process.env.HOSTNAME}` || 'local', + name: hostname(), reconnect: true, maxReconnectAttempts: -1, }; @@ -25,4 +27,36 @@ async function getNatsConnection(): Promise { return await connect(options) } -// Send Message Function here to send the message to NATS \ No newline at end of file +// Send Message Function here to send the message to NATS +export async function sendFileUpdateMessage(path: string, version: string): Promise { + const serviceName: string = "pis-data-ingress"; + const serviceId: string = hostname(); + const message: MQFileUpdate = { + service_name: "pis-data-ingress", + service_id: serviceId, + sent_timestamp: Math.floor(Date.now() / 1000), + data_type: "file", + data_kind: "pis", + payload: { + version: version, + filepath: path, + } + }; + + let nats: NatsConnection | undefined; + + try { + const nats: NatsConnection = await getNatsConnection(); + + const subject = `ingress.file.${message.data_kind}`; + + nats.publish(subject, jc.encode(message)); + + await nats.drain(); + return true + } catch (err) { + log("ERROR", `NATS: Failed to send message: ${err}`); + if (nats) {nats.close()} + return false; + } +} \ No newline at end of file