Skip to content

Instantly share code, notes, and snippets.

@dmcleish91
Created November 20, 2024 22:12
Show Gist options
  • Select an option

  • Save dmcleish91/222c60ea224ffec10ffe7e47a590ffc2 to your computer and use it in GitHub Desktop.

Select an option

Save dmcleish91/222c60ea224ffec10ffe7e47a590ffc2 to your computer and use it in GitHub Desktop.

Revisions

  1. dmcleish91 created this gist Nov 20, 2024.
    63 changes: 63 additions & 0 deletions messagebus.ts
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,63 @@
    type MessageHandler = (message: any) => void;

    class MessageBus {
    private subscribers: Map<string, MessageHandler[]> = new Map();

    // Subscribe to a specific message type
    subscribe(messageType: string, handler: MessageHandler): void {
    if (!this.subscribers.has(messageType)) {
    this.subscribers.set(messageType, []);
    }
    this.subscribers.get(messageType)!.push(handler);
    }

    // Unsubscribe a specific handler from a message type
    unsubscribe(messageType: string, handler: MessageHandler): void {
    const handlers = this.subscribers.get(messageType);
    if (handlers) {
    this.subscribers.set(
    messageType,
    handlers.filter((h) => h !== handler)
    );
    }
    }

    // Publish a message of a specific type
    publish(messageType: string, message: any): void {
    const handlers = this.subscribers.get(messageType);
    if (handlers) {
    handlers.forEach((handler) => handler(message));
    }
    }
    }

    // Usage example

    const messageBus = new MessageBus();

    // Subscriber 1
    messageBus.subscribe("orderPlaced", (message) => {
    console.log("Inventory Service: Order received:", message);
    });

    // Subscriber 2
    messageBus.subscribe("orderPlaced", (message) => {
    console.log("Notification Service: Sending confirmation for:", message);
    });

    // Publish an event
    messageBus.publish("orderPlaced", { orderId: 123, product: "Laptop", quantity: 1 });

    // Another example: Unsubscribe a handler
    const shippingHandler = (message: any) => {
    console.log("Shipping Service: Preparing package for:", message);
    };

    messageBus.subscribe("orderPlaced", shippingHandler);
    messageBus.publish("orderPlaced", { orderId: 124, product: "Phone", quantity: 2 });

    // Unsubscribe the shipping handler
    messageBus.unsubscribe("orderPlaced", shippingHandler);

    // Test after unsubscribing
    messageBus.publish("orderPlaced", { orderId: 125, product: "Tablet", quantity: 3 });