1.0.1 • Published 7 years ago

trailpack-pubsub v1.0.1

Weekly downloads
2
License
MIT
Repository
github
Last release
7 years ago

trailpack-pubsub

:package: Redis Pub/Sub implementation for Trails.js app

Gitter NPM version Build status Dependency Status Code Climate

Provides ability to send/receive messages using Redis Pub/Sub

A pretty simple Pub/Sub system between your Trails.js applications.

Install

$ npm install --save trailpack-pubsub

Usage

Configure

Load in your trailpack config

// config/main.js
module.exports = {
  // ...
  packs: [
    require('trailpack-core'),
    require('trailpack-router'),
    // ...
    require('trailpack-pubsub')
  ]
}

Configure connection

// config/pubsub.js

module.exports = {
  /**
   * Redis connection settings
   * @see {@link https://github.com/NodeRedis/node_redis#rediscreateclient}
   * @type {Object}
   */
  connection: {
    host: '127.0.0.1',
    post: 6370
  },

  /**
   * Default channel that will be used to publish events if no specific channel defined
   * @type {String}
   */
  defaultChannel: 'trails-channel',

  /**
   * List of global handlers
   * @type {Object}
   */
  handlers: {

    onSubscribe: function(channel, count) {},

    onError: function (err) {},

    onMessage: function (event, message) {}
  }
}

Don't forget to add new config file into config/index.js

exports.pubsub = require('./pubsub')

Subscribing to events

Right now you could subscribe to any event anywhere in your app

// Add a new subscription to specific event inside application
this.app.pubsub.on('event', (data) => {
  // ...
})

Another way to handle all events is handlers.onMessage() method in config/pubsub.js

module.exports = {

  //...
  handlers: {

    onMessage: function (event, message) {
      // Will handle all events/messages from other apps
    }
  }
}

Publish message

You could publish event to other applications using pubsub.publish() method

this.app.pubsub.publish('some-event', { some: 'data' })

Handling Errors

Right now there is only one place for handling errors in your app.

You could add handlers.onError function into your config/pubsub.js file

Contributing

We love contributions! Please check out our Contributor's Guide for more information on how our projects are organized and how to get started.

License

MIT