0.0.1 • Published 5 years ago

props-lib-mq v0.0.1

Weekly downloads
1
License
MIT
Repository
-
Last release
5 years ago

lib-mq

Connect to RabbitMQ in order to publish / consume messages.

The library is wrapping amqp.node client library

Connecting to Rabbit

The following will open a connection with rabbit so later publishing and consuming will be possible. Since we would like to have one single connection per running node it's best to add this to server.start in app.js The connect function already wrapping a retry mechanism in case the connection fails.

import { MQClient } from 'props-lib-mq';

MQClient.connect( RABBIT_URL );

Publishing to Rabbit

publish function signature

static async publish(exchangeName, exchangeType, key, data, correlationId = null, opts = {}):Promise<boolean>
import { MQClient } from 'props-lib-mq';

const published =  MQClient.publish('user', 'topic', 'event.success.user.join.room', { user_id: "123", room_id: "123" }).then(published => {
  if(published) console.log('Woot Woot');
  else console.error('Publish Failed');
}).catch(err){
  // Critical error
};

Consuming from rabbit

When consuming we need first to wait for a connection to be available, once that happen a 'ready' event will be emitted. The event will be emitted on each reconnection made to rabbit in case the connection was suddenly closed and had to reconnect those promising continues consuming subsequent an event of connection close / error.

consume function signature

static consume(exchangeName, exchangeType, key, queueName, opts = {}, callback)
import { MQClient, MQClientEvents } from 'props-lib-mq';

MQClientEvents.on('ready', () => {
  MQClient.consume('user', 'topic', 'event.success.user.offline', 'room-event-success-user-offline', {}, (data, ack, nack, rawMsg) => {
    
    // Handle message here
    
  });
});