Skip to content

sylaht/async-pubsub

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

27 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

Async PubSub

npm version Build Status Coverage Status License: ISC

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 event
  • unsubscribe<K extends keyof TEvents>(event: K, callback: AsyncCallback<TEvents[K]>): Unsubscribe from an event
  • publish<K extends keyof TEvents>(event: K, data: TEvents[K]): Promise<void>: Publish an event
  • once<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

  1. Fork the repository
  2. Create your feature branch (git checkout -b feature/amazing-feature)
  3. Commit your changes (git commit -m 'Add some amazing feature')
  4. Push to the branch (git push origin feature/amazing-feature)
  5. Open a Pull Request

License

ISC

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors