@teliagen/events
v0.4.2
Published
Type-safe event system for Teliagen Framework
Maintainers
Readme
@teliagen/events
Event system for the Teliagen Framework.
Overview
@teliagen/events provides a lightweight, type-safe event bus for decoupled communication:
- EventBus – Global pub/sub event system
- Typed Events – Full TypeScript support
- Async Handlers – Support for async event handlers
- Wildcard Patterns – Listen to event groups
Installation
npm install @teliagen/events
# or
pnpm add @teliagen/eventsQuick Start
import { EventBus } from '@teliagen/events';
// Subscribe to an event
EventBus.on('user:created', async (data) => {
console.log('New user created:', data.user.email);
await sendWelcomeEmail(data.user.email);
});
// Emit an event
EventBus.emit('user:created', {
user: { id: '123', email: '[email protected]' }
});API Reference
EventBus
// Subscribe to an event
EventBus.on(event: string, handler: (data: any) => void | Promise<void>): () => void;
// Subscribe once (auto-unsubscribe after first call)
EventBus.once(event: string, handler: (data: any) => void | Promise<void>): () => void;
// Unsubscribe
EventBus.off(event: string, handler: Function): void;
// Emit an event
EventBus.emit(event: string, data?: any): Promise<void>;
// Clear all handlers for an event
EventBus.clear(event?: string): void;Usage Examples
Basic Events
import { EventBus } from '@teliagen/events';
// Subscribe
const unsubscribe = EventBus.on('order:created', (data) => {
console.log('Order created:', data.orderId);
});
// Emit
await EventBus.emit('order:created', { orderId: '123', total: 99.99 });
// Unsubscribe when done
unsubscribe();One-Time Subscription
EventBus.once('app:ready', () => {
console.log('App is ready!');
initializeServices();
});
// Handler is automatically removed after first emitAsync Handlers
EventBus.on('user:registered', async (data) => {
await sendWelcomeEmail(data.email);
await createDefaultSettings(data.userId);
await notifyAdmins(data);
});
// Emit waits for all handlers to complete
await EventBus.emit('user:registered', { userId: '123', email: '[email protected]' });
console.log('All handlers completed');Error Handling
EventBus.on('payment:processed', async (data) => {
try {
await updateOrderStatus(data.orderId, 'paid');
} catch (error) {
console.error('Failed to update order:', error);
// Error is caught, doesn't break other handlers
}
});Event Naming Conventions
Use namespaced event names:
// Format: domain:action
'user:created'
'user:updated'
'user:deleted'
'order:placed'
'order:shipped'
'payment:processed'
'auth:login'
'auth:logout'Framework Events
Teliagen plugins emit events you can listen to:
Auth Plugin
EventBus.on('auth:registered', async ({ user }) => { ... });
EventBus.on('auth:login', async ({ user }) => { ... });
EventBus.on('auth:logout', async ({ userId }) => { ... });
EventBus.on('auth:passwordReset', async ({ user, token }) => { ... });Tenant Plugin
EventBus.on('tenant:created', async ({ tenant, owner }) => { ... });
EventBus.on('tenant:memberAdded', async ({ tenantId, userId, role }) => { ... });
EventBus.on('tenant:invitationSent', async ({ invitation }) => { ... });RBAC Plugin
EventBus.on('rbac:roleAssigned', async ({ userId, roleId }) => { ... });
EventBus.on('rbac:roleRevoked', async ({ userId, roleId }) => { ... });Storage Plugin
EventBus.on('storage:uploaded', async ({ disk, path, size }) => { ... });
EventBus.on('storage:deleted', async ({ disk, path }) => { ... });Mail Plugin
EventBus.on('mail:sent', async ({ to, subject }) => { ... });
EventBus.on('mail:failed', async ({ to, error }) => { ... });Usage in Actions
import { Action, ActionProvider, Input } from '@teliagen/commons';
import { EventBus } from '@teliagen/events';
@ActionProvider('orders', 'OrderActions')
class OrderActions {
@Action('createOrder')
async createOrder(@Input() input: CreateOrderInput) {
const order = await Order.create(input);
// Emit event for other systems to react
await EventBus.emit('order:created', {
orderId: order.id,
userId: input.userId,
total: order.total
});
return order;
}
}Type-Safe Events
// Define event types
interface AppEvents {
'user:created': { user: User };
'order:placed': { orderId: string; total: number };
'notification:send': { userId: string; message: string };
}
// Create typed event bus
import { createTypedEventBus } from '@teliagen/events';
const events = createTypedEventBus<AppEvents>();
// Now fully typed!
events.on('user:created', (data) => {
console.log(data.user.email); // TypeScript knows about user
});
events.emit('order:placed', {
orderId: '123',
total: 99.99
});Requirements
- Node.js >= 18.0.0
- TypeScript >= 5.0.0 (for typed events)
Documentation
For full documentation, visit docs.teliagen.org.
License
Apache-2.0
