Package Exports
- ts-async-pubsub
- ts-async-pubsub/dist/index.js
This package does not declare an exports field, so the exports above have been automatically detected and optimized by JSPM instead. If any package subpath is missing, it is recommended to post an issue to the original package (ts-async-pubsub) to support the "exports" field. If that is not possible, create a JSPM override to customize the exports field for this package.
Readme
Async PubSub
A lightweight, type-safe event bus implementation in TypeScript that supports asynchronous event handling.
Features
- ๐ Type-safe event handling with TypeScript
- โก Asynchronous event processing
- ๐ฏ Support for one-time event listeners
- ๐ก๏ธ Error handling for event listeners
- ๐ฆ Zero dependencies
- ๐งช Jest testing setup included
Installation
npm install ts-async-pubsub
Usage
Basic Setup
import { AsyncEventBus } from 'ts-async-pubsub';
// Define your event types
type EventMap = {
userCreated: { name: string; email: string };
orderPlaced: { orderId: string; amount: number };
};
// Create an instance of the event bus
const bus = new AsyncEventBus<EventMap>();
Subscribing to Events
// Regular subscription
bus.subscribe('userCreated', async (user) => {
console.log('New user:', user.name);
});
// One-time subscription
bus.once('userCreated', async (user) => {
console.log('Welcome,', user.name);
});
Publishing Events
// Publish an event
await bus.publish('userCreated', {
name: 'John Doe',
email: 'john@example.com'
});
Unsubscribing from Events
const handler = async (user: EventMap['userCreated']) => {
console.log('User created:', user.name);
};
bus.subscribe('userCreated', handler);
// Later...
bus.unsubscribe('userCreated', handler);
Error Handling
// The event bus automatically handles errors in listeners
bus.subscribe('userCreated', async (user) => {
throw new Error('Something went wrong');
// Other listeners will still be called
});
// You can also handle errors in your listeners
bus.subscribe('userCreated', async (user) => {
try {
await processUser(user);
} catch (error) {
console.error('Failed to process user:', error);
}
});
Advanced Usage
Multiple Event Types
type EventMap = {
userCreated: { name: string; email: string };
orderPlaced: { orderId: string; amount: number };
paymentProcessed: { orderId: string; status: 'success' | 'failed' };
};
const bus = new AsyncEventBus<EventMap>();
// Subscribe to multiple events
bus.subscribe('userCreated', async (user) => {
// Handle user creation
});
bus.subscribe('orderPlaced', async (order) => {
// Handle order placement
});
Async Event Processing
bus.subscribe('orderPlaced', async (order) => {
// Simulate async processing
await new Promise(resolve => setTimeout(resolve, 1000));
console.log('Order processed:', order.orderId);
});
One-time Event Listeners
// This listener will be called only once
bus.once('userCreated', async (user) => {
console.log('First user created:', user.name);
});
API Reference
AsyncEventBus<TEvents>
The main class that handles event management.
Methods
subscribe<K extends keyof TEvents>(event: K, callback: AsyncCallback<TEvents[K]>)
: Subscribe to an eventunsubscribe<K extends keyof TEvents>(event: K, callback: AsyncCallback<TEvents[K]>)
: Unsubscribe from an eventpublish<K extends keyof TEvents>(event: K, data: TEvents[K]): Promise<void>
: Publish an eventonce<K extends keyof TEvents>(event: K, callback: AsyncCallback<TEvents[K]>)
: Subscribe to an event once
Development
Setup
# Install dependencies
npm install
# Run tests
npm test
# Run tests in watch mode
npm run test:watch
# Check test coverage
npm run test:coverage
Project Structure
src/
โโโ EventBus.ts # Main implementation
โโโ types/ # Type definitions
โโโ __tests__/ # Test files
โโโ demo.ts # Usage example
Contributing
- Fork the repository
- Create your feature branch (
git checkout -b feature/amazing-feature
) - Commit your changes (
git commit -m 'Add some amazing feature'
) - Push to the branch (
git push origin feature/amazing-feature
) - Open a Pull Request
License
ISC