Why "pubsub-api" is the TypeScript eventing library you’ve been waiting for
Tags: opensource, typescript, frontend, webdev
Published: 2023-11-01 02:15:00

## Introduction

Event handling in TypeScript can be a tricky area. In particular, there's a significant absence of native constructs to manage events apart from those tied to DOM elements. This absence often forces developers into using external libraries or various hacks to achieve functionality that should, ideally, be straightforward. `pubsub-api` was created to fill this gap, offering not just an event handling system, but one that is tailor-made to integrate seamlessly with TypeScript's strong typing features. It's more than a stop-gap; it’s a robust solution designed with modern TypeScript development in mind.

---

## What's Our Next Move?

### Messaging Patterns: From Observer to Mediator

Traditional messaging patterns like the Observer pattern can sometimes create more problems than they solve. For example, they might introduce tight coupling between components, making the codebase hard to maintain and scale. The Mediator pattern could alleviate this issue, but it often becomes a complex piece of architecture on its own, leading to a monolithic code structure that is equally difficult to manage. Therefore, a simpler yet effective solution is needed.

### The PubSub Pattern: Why It Stands Out

The Publish-Subscribe (PubSub) pattern has the benefits of decoupling the sender and receiver, which is extremely beneficial in TypeScript applications. It lets you focus on writing scalable and maintainable code, without worrying about the underlying communication mechanism between components. This decoupling is incredibly useful when you are working with large codebases or when you need the flexibility to change parts of your system independently.

---

## Why `pubsub-api`?

### Target Goals and Special Features

`pubsub-api` aims to offer not only support for generic events, but also the ability to use strongly typed custom payloads, effectively turning your event data into self-checking intelligent constructs.

### Unique Characteristics: What Really Sets It Apart

One aspect that sets `pubsub-api` apart is its flexibility in managing topics. You can either define and type each topic individually for specific use cases or bundle multiple topics into a single object for centralized management. This dual approach allows for both fine-grained control when you need it and the ability to streamline your codebase by centralizing topic management.

In contrast to other libraries, `pubsub-api` is not a JavaScript library that has been retrofitted to support TypeScript. It’s been designed from the ground up with TypeScript's unique features in mind. The focus on strong typing extends to even the smallest features, including its API for dynamically generated topics and its asynchronous event queue.

---

## Installation and Getting Started

To install `pubsub-api`, run:

```bash
npm install pubsub-api
```

Imagine a chat application where a user can join multiple rooms. Using `pubsub-api`, you can easily manage events like "new message", "user joined", or "user left".

```ts
// chat.ts
import { pubSub } from 'pubsub-api';  
// Define the topics interface
type ChatTopics = {
	user: [userId: string, roomId: number, status: 'joined' | 'left'];
	newMessage: (roomId: number, message: string) => void;
}
// Create a PubSub instance for notification events
export const chat = pubSub<ChatTopics>();
```

```ts
// your-ui.ts
import { chat } from './chat';
// Subscribe to new message events to update UI
chat.topic('user').sub((userId, roomId, status) => {
  console.log(`User '${userId}' ${status} the room ${roomId}`);
});
chat.topic('newMessage').sub((roomId, message) => {
  console.log(`New message in room ${roomId}: '${message}'`);
});
```

```ts
// your-logic.ts
import { chat } from './chat';
const user = chat.topic('user');
const newMessage = chat.topic('newMessage');
// Simulate user interactions by publishing events
user.pub('TypeScript', 5, 'joined');
newMessage.pub(5, 'Hello, World!');
newMessage.pub(5, 'My name is pubsub-api!');
user.pub('TypeScript', 5, 'left');
```

---

## Advanced Capabilities: Digging Deeper

### Topics in Full Swing

The feature-rich, type-safe topics in `pubsub-api` are a developer’s dream. They offer built-in error checking, which not only catches mistakes earlier but also allows IDEs to provide more intelligent suggestions and auto-completions. This saves a huge amount of debugging and development time.

### The Asynchronous Edge

One of the library’s lesser-known but beneficial features is its asynchronous event queue. Events are not processed immediately; instead, they are batched together and processed in a way that optimizes performance, especially during high-load situations. This design ensures that the system remains responsive even when flooded with events.

---

## Conclusion: Who Should Use This and When

`pubsub-api` is not just for those who need to cobble together some quick event-handling code. It’s for developers who need a comprehensive, robust, and type-safe solution for managing complex event-driven architectures in TypeScript. It's particularly useful for larger projects where maintainability and scalability are crucial.

### Inviting You to Get Hands-On!

If you constantly deal with intricate event-handling scenarios in TypeScript, then `pubsub-api` is worth a try. Not only will it make your development process smoother, but it will also improve the quality of your code. We invite you to take it for a spin, provide feedback, and even contribute to its continued development.

### Links

- [Find it on npm](https://npm.im/pubsub-api)
- [GitHub Repository](https://github.com/adv0cat/pubsub-api)