Skip to content

Instantly share code, notes, and snippets.

@dmcleish91
Created November 20, 2024 22:12
Show Gist options
  • Save dmcleish91/222c60ea224ffec10ffe7e47a590ffc2 to your computer and use it in GitHub Desktop.
Save dmcleish91/222c60ea224ffec10ffe7e47a590ffc2 to your computer and use it in GitHub Desktop.
An example implementation of a simple message bus in TypeScript using the publish-subscribe pattern
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 });
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment