61 lines
1.9 KiB
TypeScript
61 lines
1.9 KiB
TypeScript
import { type HeartbeatSent } from "../../../cloudevents/com.plugis/heartbeat/Sent/types/ts/heartbeatSent.d";
|
|
import { CloudEvent } from "cloudevents";
|
|
import NatsClass from "./NatsClass";
|
|
import process from "node:process";
|
|
import { PlugisClass } from "./PlugisClass";
|
|
|
|
const nats = new PlugisClass("ws://nats.plugis.cloud:8222");
|
|
await nats.connect();
|
|
console.log("server version", nats.serverVersion());
|
|
|
|
// publish a heartbeat cloud event every 30 seconds
|
|
setInterval(() => {
|
|
const heartbeatSent: HeartbeatSent = {
|
|
hostname: process.env.HOSTNAME || require('os').hostname(),
|
|
timestamp: new Date().toISOString(),
|
|
mac: "00:11:22:33:44:55",
|
|
ip: "192.168.1.100",
|
|
started: new Date().toISOString(),
|
|
uptime: 1000,
|
|
version: "1.0.0",
|
|
"nats-service": "test-service",
|
|
os: process.platform,
|
|
arch: process.arch
|
|
};
|
|
const ce = new CloudEvent({
|
|
type: "com.plugis.heartbeat.Sent",
|
|
source: `${import.meta.url}#${new Error().stack?.split('\n')[1]?.split(':')[1] || '0'}`,
|
|
data: heartbeatSent,
|
|
});
|
|
nats.publishJson("com.plugis.heartbeat.Sent.TEST", ce);
|
|
}, 1000*60);
|
|
|
|
// subscribe using a callback
|
|
const _sub = nats.subscribeCb("remote.*.event", (err, msg) => {
|
|
if (err) {
|
|
console.error("error", err);
|
|
return;
|
|
}
|
|
const ce = msg.json<CloudEvent<Waypoint>>();
|
|
const waypoint = ce.data as Waypoint;
|
|
|
|
console.log("msg", msg.subject, "data", msg.string());
|
|
});
|
|
|
|
// subscribe using an iterator
|
|
const cloudEventsIterator = nats.subscribeToType<CloudEvent<HeartbeatSent>>("com.plugis.heartbeat.Sent.>");
|
|
(async () => {
|
|
for await (const ce of cloudEventsIterator) {
|
|
const heartbeatSent = ce.data as HeartbeatSent;
|
|
console.log("received cloud event", ce);
|
|
}
|
|
})();
|
|
|
|
// wait until the process is interrupted
|
|
await nats.interrupted;
|
|
console.log("interrupted");
|
|
|
|
// close nats connection
|
|
await nats.close();
|
|
console.log("nats.close done");
|
|
process.exit(0);
|