UNPKG

@sailboat-computer/event-bus

Version:

Standardized event bus for sailboat computer v3 with resilience features and offline capabilities

156 lines (134 loc) 3.78 kB
/** * Basic usage example for the event bus */ import { createEventBus, EventPriority, EventCategory } from '../src'; // Define event types interface UserCreatedEvent { id: string; username: string; email: string; createdAt: Date; } interface OrderPlacedEvent { id: string; userId: string; items: Array<{ productId: string; quantity: number; price: number; }>; total: number; placedAt: Date; } async function main() { console.log('Starting event bus example...'); // Create event bus const eventBus = createEventBus({ adapter: { type: 'memory', config: { serviceName: 'example-service' } }, offlineBuffer: { maxSize: 1000, priorityRetention: true }, metrics: { enabled: true, detailedTimings: true } }); // Initialize event bus await eventBus.initialize({ adapter: { type: 'memory', config: { serviceName: 'example-service' } }, offlineBuffer: { maxSize: 1000, priorityRetention: true }, metrics: { enabled: true, detailedTimings: true } }); console.log('Event bus initialized'); // Subscribe to user created events const userSubscription = await eventBus.subscribe<UserCreatedEvent>('user.created.v1', async (event) => { console.log(`User created: ${event.data.username} (${event.data.email})`); }); console.log(`Subscribed to user created events with ID: ${userSubscription.id}`); // Subscribe to order placed events const orderSubscription = await eventBus.subscribe<OrderPlacedEvent>('order.placed.v1', async (event) => { console.log(`Order placed: ${event.data.id} by user ${event.data.userId}`); console.log(`Total: $${event.data.total.toFixed(2)}`); console.log(`Items: ${event.data.items.length}`); }); console.log(`Subscribed to order placed events with ID: ${orderSubscription.id}`); // Publish a user created event const userId = 'user-123'; await eventBus.publish<UserCreatedEvent>( 'user.created.v1', { id: userId, username: 'sailor', email: 'sailor@example.com', createdAt: new Date() }, { priority: EventPriority.NORMAL, category: EventCategory.USER_ACTION, tags: ['user', 'registration'] } ); // Publish an order placed event await eventBus.publish<OrderPlacedEvent>( 'order.placed.v1', { id: 'order-456', userId: userId, items: [ { productId: 'product-1', quantity: 2, price: 10.99 }, { productId: 'product-2', quantity: 1, price: 24.99 } ], total: 2 * 10.99 + 24.99, placedAt: new Date() }, { priority: EventPriority.HIGH, category: EventCategory.DATA, correlationId: userId, tags: ['order', 'purchase'] } ); // Wait for events to be processed await new Promise(resolve => setTimeout(resolve, 100)); // Get metrics const metrics = eventBus.getMetrics(); console.log('\nEvent Bus Metrics:'); console.log(`- Published events: ${metrics.publishedEvents}`); console.log(`- Failed publishes: ${metrics.failedPublishes}`); console.log(`- Processed events: ${metrics.processedEvents}`); console.log(`- Active subscriptions: ${metrics.activeSubscriptions}`); console.log(`- Average processing time: ${metrics.averageProcessingTime.toFixed(2)}ms`); // Unsubscribe await userSubscription.unsubscribe(); await orderSubscription.unsubscribe(); console.log('\nUnsubscribed from all events'); // Close event bus await eventBus.close(); console.log('Event bus closed'); } // Run the example main().catch(error => { console.error('Error in example:', error); process.exit(1); });