forked from nathydre21/nepa
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathEventBus.ts
More file actions
57 lines (49 loc) · 1.41 KB
/
EventBus.ts
File metadata and controls
57 lines (49 loc) · 1.41 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
// Event Bus for inter-service communication
import { EventEmitter } from 'events';
export interface DomainEvent {
eventId: string;
eventType: string;
aggregateId: string;
timestamp: Date;
payload: any;
metadata?: {
userId?: string;
correlationId?: string;
causationId?: string;
};
}
class EventBus extends EventEmitter {
private static instance: EventBus;
private constructor() {
super();
this.setMaxListeners(100); // Increase for multiple services
}
static getInstance(): EventBus {
if (!EventBus.instance) {
EventBus.instance = new EventBus();
}
return EventBus.instance;
}
publish(event: DomainEvent): void {
console.log(`📤 Publishing event: ${event.eventType}`, {
eventId: event.eventId,
aggregateId: event.aggregateId,
});
this.emit(event.eventType, event);
this.emit('*', event); // Wildcard for logging/monitoring
}
subscribe(eventType: string, handler: (event: DomainEvent) => Promise<void>): void {
this.on(eventType, async (event: DomainEvent) => {
try {
await handler(event);
} catch (error) {
console.error(`❌ Error handling event ${eventType}:`, error);
// Implement retry logic or dead letter queue here
}
});
}
subscribeAll(handler: (event: DomainEvent) => Promise<void>): void {
this.subscribe('*', handler);
}
}
export default EventBus.getInstance();