npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

pubsub-api

v0.2.1

Published

Topic-based PubSub pattern implementation for TypeScript

Downloads

39

Readme

pubsub-api

npm version downloads bundle size npm type definitions GitHub license

pubsub-api is a type-safe topic-based Publish-Subscribe (PubSub) pattern implementation for TypeScript. Its lightweight design coupled with a simple API facilitates clean, decoupled architecture, allowing seamless communication across your application.

Features

  • Performance: Efficient subscription and unsubscription with minimal overhead.
  • 🧩 Modularity: Seamlessly define, reuse, and extend your topics and message types across your application.
  • Simple API: Straightforward and intuitive API for publishing and subscribing to topics.
  • Type Safety: Strongly-typed topics and messages to ensure contract adherence and catch issues at compile-time.
  • 🪶 Lightweight: Minimal footprint on your project's bundle size.
  • ♻️ Zero Dependencies: Standalone library with no external dependencies.

Installation

Install pubsub-api via npm:

npm install pubsub-api --save

Or via yarn:

yarn add pubsub-api

Quick Start

// Import the pubSub function from the library
import { pubSub } from "pubsub-api";

// Create a PubSub instance
const pub = pubSub();

// Define a topic for like events
const likeTopic = pub.topic("like");

// Subscribe to the like topic to log like events
const unsubscribe = likeTopic.sub((likeData) => {
  console.log(`Post ID: ${likeData.postId}, was liked!`);
});

// Simulate a like event by publishing a message to the like topic
likeTopic.pub({ postId: "abc123" });

// Optionally unsubscribe later
unsubscribe();

This basic flow demonstrates the core functionalities of pubsub-api, helping you to set up a simple real-time messaging mechanism.

Usage

Defining Message and Topics Interfaces

In this section, we define interfaces for different types of notification events and create a PubSub instance for managing these events.

// Import the necessary functions from the library
import { pubSub } from "pubsub-api";

// Define the topics interface
interface Topics {
  newContact: string;
  newMessage: (message: string, sender: string, timestamp: number) => void;
  messageDeletion: [messageId: string];
}

// Create a PubSub instance for notification events
const notifier = pubSub<Topics>();

Subscribing to Topics

Here we demonstrate how to subscribe to different topics to receive and handle notification events.

// Subscribe to new message events to update UI
notifier.topic("newMessage").sub((message, sender, timestamp) => {
  console.log(
    `New message from ${sender} at ${new Date(timestamp)}: ${message}`,
  );
});

// Subscribe to new contact events to update UI
notifier.topic("newContact").sub((contactName) => {
  console.log(`New contact added: ${contactName}`);
});

// Subscribe to message deletion events to update UI
notifier.topic("messageDeletion").sub((messageId) => {
  console.log(`Message with ID ${messageId} was deleted.`);
});

Publishing to Topics

In this section, we simulate user interactions by publishing realistic events to the topics.

// Simulate user interactions by publishing events
notifier
  .topic("newMessage")
  .pub("Hey, are you coming to the meeting?", "Alice", Date.now());
notifier.topic("newContact").pub("Bob Johnson");
notifier.topic("messageDeletion").pub("msg1234567890");

Unsubscribing All Subscribers

You have the ability to unsubscribe all subscribers from a specific topic or from all topics in a PubSub instance using the unSubAll method.

// Unsubscribe all subscribers from a specific topic
notifier.topic("newMessage").unSubAll();
notifier.topic("newContact").unSubAll();
notifier.topic("messageDeletion").unSubAll();

// Unsubscribe all subscribers from all topics in the PubSub instance
notifier.unSubAll();

Advanced Usage

Creating Topics Separately

You can also create topics separately from the PubSub instance, either with or without specifying a type.

In this example, we create a topic for handling new group creation events, demonstrating how you can manage topics separately from a PubSub instance.

// Import the topic function from the library
import { topic } from "pubsub-api";

// Create a topic for new group events
const groups = topic<[groupName: string]>();

// Subscribe to new group events to update UI
groups.sub((groupName) => {
  console.log(`New group created: ${groupName}`);
});

// Simulate a new group creation event by publishing to the topic
groups.pub("Project Discussion");

Using Context with Subscribers

You can provide a context object when subscribing to a topic, which will be used as the this value when the subscriber function is called.

interface User {
    name: string;
}

const user: User = {
    name: 'Alice',
};

notifier.topic('newMessage').sub(function (message, sender, timestamp) {
    console.log(`${this.name} received a new message from ${sender} at ${new Date(timestamp)}: ${message}`);
}, user);

// Simulate user interactions by publishing events
notifier.topic('newMessage').pub('Hey, are you coming to the meeting?', 'Bob', Date.now());

One-Time Subscriptions

You can create a one-time subscription to a topic using the once method. The subscription will be automatically removed after the first message is received.

// Subscribe to new message events for a one-time notification
notifier.topic('newMessage').once((message, sender, timestamp) => {
    console.log(`One-time notification: New message from ${sender} at ${new Date(timestamp)}: ${message}`);
});

// Simulate user interactions by publishing events
notifier.topic('newMessage').pub('Hey, are you coming to the meeting?', 'Bob', Date.now());

Documentation

Currently, the documentation is being developed. However, you can find a couple of examples for each module within the library to get started. More comprehensive documentation will be provided in the near future.