@sailboat-computer/event-bus
Version:
Standardized event bus for sailboat computer v3 with resilience features and offline capabilities
168 lines (142 loc) • 4.18 kB
text/typescript
/**
* Schema validation example
*
* This example demonstrates how to use schema validation with the event bus.
*/
import { createEventBus, EventPriority, EventCategory } from '../src';
// Define a schema for a user created event
const userCreatedSchema = {
type: 'object',
properties: {
id: { type: 'string' },
username: { type: 'string' },
email: { type: 'string', format: 'email' },
createdAt: { type: 'string', format: 'date-time' }
},
required: ['id', 'username', 'email'],
additionalProperties: false
};
// Define the event type
interface UserCreatedEvent {
id: string;
username: string;
email: string;
createdAt: string;
}
async function runExample() {
console.log('Starting schema validation example...');
// Create event bus
const eventBus = createEventBus({
adapter: {
type: 'memory',
config: {
serviceName: 'schema-validation-example'
}
},
offlineBuffer: {
maxSize: 100,
priorityRetention: true
},
metrics: {
enabled: true,
detailedTimings: true
}
});
// Initialize event bus
await eventBus.initialize({
adapter: {
type: 'memory',
config: {
serviceName: 'schema-validation-example'
}
},
offlineBuffer: {
maxSize: 100,
priorityRetention: true
},
metrics: {
enabled: true,
detailedTimings: true
}
});
// Register schema for user.created.v1 event
eventBus.registerSchema<UserCreatedEvent>('user.created.v1', userCreatedSchema);
console.log('Registered schema for user.created.v1 event');
// Subscribe to user created events
await eventBus.subscribe<UserCreatedEvent>('user.created.v1', (event) => {
console.log(`User created: ${event.data.username} (${event.data.email})`);
});
console.log('Subscribed to user.created.v1 events');
// Publish a valid event
try {
const validEvent: UserCreatedEvent = {
id: '123',
username: 'sailor',
email: 'sailor@example.com',
createdAt: new Date().toISOString()
};
console.log('Publishing valid event:', validEvent);
await eventBus.publish<UserCreatedEvent>(
'user.created.v1',
validEvent,
{
priority: EventPriority.NORMAL,
category: EventCategory.USER_ACTION
}
);
console.log('Valid event published successfully');
} catch (error) {
console.error('Failed to publish valid event:', error);
}
// Publish an invalid event (missing required field)
try {
const invalidEvent = {
id: '456',
username: 'captain',
// Missing email field
createdAt: new Date().toISOString()
};
console.log('Publishing invalid event (missing email):', invalidEvent);
await eventBus.publish<UserCreatedEvent>(
'user.created.v1',
invalidEvent as any,
{
priority: EventPriority.NORMAL,
category: EventCategory.USER_ACTION
}
);
console.log('Invalid event published successfully (this should not happen)');
} catch (error) {
console.error('Failed to publish invalid event (expected):', error.message);
}
// Publish an invalid event (additional property)
try {
const invalidEvent = {
id: '789',
username: 'admiral',
email: 'admiral@example.com',
createdAt: new Date().toISOString(),
role: 'admin' // Additional property not in schema
};
console.log('Publishing invalid event (additional property):', invalidEvent);
await eventBus.publish<UserCreatedEvent>(
'user.created.v1',
invalidEvent as any,
{
priority: EventPriority.NORMAL,
category: EventCategory.USER_ACTION
}
);
console.log('Invalid event published successfully (this should not happen)');
} catch (error) {
console.error('Failed to publish invalid event (expected):', error.message);
}
// Close event bus
await eventBus.close();
console.log('Schema validation example completed');
}
// Run the example
runExample().catch(error => {
console.error('Example failed:', error);
process.exit(1);
});