ts-post
v2.0.0
Published
Flexible PubSub messaging bus system for node and browser applications
Downloads
5
Maintainers
Readme
ts-post
Install
In terminal, run:
npm i ts-post
Basic usage
ts-post allows you to create multiple buses to better segment and handle what messages the subscribers will receive or not.
This encourages you to have a well defined type for message data going through each bus, helping limiting potential errors where callbacks would have tried to handle different objects than expected.
The singleton instance of Port has to be created globally, in order to be accessible everywhere in your app without risk of undelivered messages.
By default, a bus named default
is created.
Import
import { Message, Post, Subscription } from 'ts-post';
Example
const post = Post.getInstance;
// Create a new bus called foo, which will dispatch messages only to foo subcribers
post.createBus('foo');
// Subscribe to the bus
const sub = post.subscribe('foo', {
callback: async (message: Message) => {
console.log(`Message timestamp: ${message.getTimestamp()} - issuer: ${message.getIssuer()}`);
await doSomethingWithData(message.getData());
},
errorHandler: (error) => { console.error(error); }
});
// Publish a message into the bus
await post.publish('foo', new Message({ id: 'bar', description: 'some data', available: 104 }, 'FooService'));
// Unsubscribe
sub.unsubscribe();
Options and data
Subscriber
The available options are:
callback
(required): the callback to execute when receiving a messageerrorHandler
(optional): the callback to execute in case of exception while executing the callbackdelay
(optional): the delay before executing the callback- If undefined, the callback will be executed immediatly and synchronously (according to its order in the subscribers list)
- If >= 0, the callback will be put in the event loop using
setTimeout
When subscribing, the returned subscriber can call .unsubscribe()
to remove the subscription to the bus.
Message
When creating a message to be published, the options are:
data
(required): the actual data to sendissuer
(optional): the app component/service/... responsible for the message publishing
The data sent is packaged with additional info:
getData
returns the data sent in the messagegetTimestamp
returns the creation time (in ms) of the messagegetIssuer
returns the issuer of the message (if defined)
Contribute
Please feel free to suggest features or bug fix through Git issues. Pull Requests for that are also more than welcome.