Event-driven microservice — communicate via events.
1const { EventEmitter } = require("events");2const amqp = require("amqplib");34class EventDrivenService {5 constructor(name) {6 this.name = name;7 this.emitter = new EventEmitter();8 this.connection = null;9 this.channel = null;10 }1112 async connect() {13 this.connection = await amqp.connect("amqp://localhost");14 this.channel = await this.connection.createChannel();15 await this.channel.assertExchange(this.name, "fanout", { durable: true });16 }1718 async publish(event) {19 this.emitter.emit(event.type, event);20 const msg = Buffer.from(JSON.stringify(event));21 this.channel.publish(this.name, "", msg);22 }2324 async subscribe(exchange, handler) {25 await this.channel.assertExchange(exchange, "fanout", { durable: true });26 const q = await this.channel.assertQueue("", { exclusive: true });27 await this.channel.bindQueue(q.queue, exchange, "");2829 this.channel.consume(q.queue, (msg) => {30 const event = JSON.parse(msg.content.toString());31 handler(event);32 this.channel.ack(msg);33 });34 }3536 on(eventType, handler) {37 this.emitter.on(eventType, handler);38 }39}4041// Usage42const orderService = new EventDrivenService("orders");43await orderService.connect();4445orderService.on("OrderCreated", async (event) => {46 console.log("Order created:", event.data);47 await sendConfirmation(event.data.userId);48});4950await orderService.publish({51 type: "OrderCreated",52 data: { id: 123, userId: "user-1" },53});