/** * Simple proof-of-concept NATS subscriber * Subscribes to mm.16.> and replies with "hello world" */ import { connect, StringCodec } from "nats"; import { logger } from "../../services/reporting-service/index.js"; const sc = StringCodec(); async function startTestSubscriber() { try { // Connect to NATS server const nc = await connect({ servers: "nats://localhost:4222", name: "mm-erp-sdk-test-subscriber", }); logger.info("Connected to NATS server", { server: nc.getServer(), clientId: nc.info?.client_id, }); // Subscribe to all messages on mm.16.> const sub = nc.subscribe("mm.16.>"); logger.info("Subscribed to mm.16.> - waiting for messages..."); // Process incoming messages (async () => { for await (const msg of sub) { const data = sc.decode(msg.data); logger.info("📨 Received NATS message", { subject: msg.subject, data: data, reply: msg.reply, }); console.log("\n=== NATS MESSAGE RECEIVED ==="); console.log("Subject:", msg.subject); console.log("Data:", data); console.log("Reply subject:", msg.reply); console.log("============================\n"); // Reply if there's a reply subject if (msg.reply) { const replyMessage = JSON.stringify({ message: "hello world", timestamp: new Date().toISOString(), receivedSubject: msg.subject, receivedData: data, }); msg.respond(sc.encode(replyMessage)); logger.info("✅ Sent reply: hello world", { replySubject: msg.reply, }); console.log("✅ Replied with: hello world\n"); } } })(); // Handle connection events (async () => { for await (const status of nc.status()) { logger.info("NATS connection status", { type: status.type, data: status.data, }); console.log(`Connection status: ${status.type}`, status.data); } })(); // Graceful shutdown const shutdown = async () => { logger.info("Shutting down NATS subscriber..."); await nc.drain(); process.exit(0); }; process.on("SIGINT", shutdown); process.on("SIGTERM", shutdown); } catch (error) { logger.error("Failed to connect to NATS", { error }); console.error("Error connecting to NATS:", error); process.exit(1); } } // Start the subscriber startTestSubscriber();