JSPM

ts-async-pubsub

1.0.1
  • ESM via JSPM
  • ES Module Entrypoint
  • Export Map
  • Keywords
  • License
  • Repository URL
  • TypeScript Types
  • README
  • Created
  • Published
  • 0
  • Score
    100M100P100Q21078F
  • License ISC

A lightweight, type-safe event bus implementation in TypeScript that supports asynchronous event handling

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

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