@darkhogg/pubsub

0.3.0 • Public • Published

@darkhogg/pubsub

npm (scoped)

A simple Publish/Subscribe system with persistent messages that uses MongoDB as a backend.

This is a toy project, created mostly to prove a point. It is usable and might solve somebody's problem, but its feature set is unlikely to grow. You are still welcome to report bugs or suggest improvements, and I will try to find time to look at them.

Usage

The API is really simple, most of it can be understood just by looking at the examples directory.

You should import this library as follows:

const {createPubSub} = require('@darkhogg/pubsub');

createPubSub(mongoUri, {bucket, clientName, startDate})

Returns a promise to a PubSub client that connects to the given mongoUri. The client will respect the database given by the URI.

  • bucket is used as the prefix of all collections. Defaults to 'pubsub'.
  • clientName is a string is used to identify this client and is used to determine which events were already consumed by it. No more that one client with the same name will ever consume the same message. Defaults to 'default'.
  • startDate is a Date determining the first date at which this client is interested in events. This is useful to prevent processing a huge number of past events for new clients that are only interested in future events. Defaults to new Date(0) (that is, 1970-01-01T00:00:00.000Z)

Note that this is the only exported symbol by the library itself.

PubSub.channel(channelName)

Returns a promise to a Channel with the given channelName. Channels are cached, so multiple calls to this method will resolve to the same object. Each channel comes with its own collection in the database.

PubSub.disconnect()

Disconnects the client and returns a promise to the successful disconnection. this will stop all channels and close the MongoDB connection. The client or any channels created by it are unusable after this call.

Channel.publish(name, body)

Publishes a message with the given name and body in this channel. Returns a promise that resolves after the message was published.

Channel.subscribe(name, callback)

Registers the callback to be called whenever a message with the given name is published. the callback is called with the message body as its argument. Returns a Subscription.

Channel.unsubscribeAll()

Cancels all subscription to this channel. No more messages will arrive to any subscriptors of this channel object.

New subscriptions can still be created normally after this call.

Subscription.unsubscribe

Cancel the subscription. No more messages will arrive to this particular subscriptor, but others will still receive messages.

New subscriptions can still be created normally after this call.

Readme

Keywords

none

Package Sidebar

Install

npm i @darkhogg/pubsub

Weekly Downloads

1

Version

0.3.0

License

MIT

Unpacked Size

9.82 kB

Total Files

10

Last publish

Collaborators

  • darkhogg