1.0.3 • Published 2 years ago

@xcore24/pubsub v1.0.3

Weekly downloads
-
License
ISC
Repository
-
Last release
2 years ago

pubsub

pubsub is TypeScript library implementing the Publish/Subscribe pattern.

Installation

To start using pubsub install the npm package:

npm install pubsub

Also you need to configure your TypeScript to enable experimental decorators. Add this line to your tsconfig.json file under the compilerOptions key:

"experimentalDecorators": true,

Basic Usage

import { PubSub, Subscribe, Subscriber, Unsubscribe } from 'pubsub';

const CONTRACT_TEST_EVENT_NAME = 'messages/test'

@Subscriber()
class SubscriberExample {
  @Subscribe(CONTRACT_TEST_EVENT_NAME)
  foo(data: string, message: string): void {
    console.log(`Message received: ${message}, Data: ${data}`);
  }

  @Unsubscribe() // Calling the method marked with @Unsibscribe() will unregister all the subscriptions
  dispose(): void {}
}

var subscriber = new SubscriberExample();
PubSub.publish(CONTRACT_TEST_EVENT_NAME, 'This message will be displayed');
subscriber.dispose(); // Unsubscribe
PubSub.publish(CONTRACT_TEST_EVENT_NAME, "This message won't be displayed");

You can also create channels to publish messages manually and specify which one you want to observe:

const myChannel = new Channel<string>();

@Subscriber({ channel: myChannel })
class SubscriberExample {
  @Subscribe(CONTRACT_TEST_EVENT_NAME)
  foo(data: string, message: string): void {
    console.log(`Message received: ${message}, Data: ${data}`);
  }
}

const data = {
  // Some data here
};
myChannel.publish(CONTRACT_TEST_EVENT_NAME, data);

If needed, you can mark a method with multiple @Subscribe() decorators to observe different messages:

@Subscriber()
class SubscriberExample {
  @Subscribe(CONTRACT_TEST_EVENT_NAME)
  @Subscribe('OTHER_MESSAGE')
  foo(data: string, message: string): void {
    console.log(`Message received: ${message}, Data: ${data}`);
  }
}