plain/plain_consumer.js

const MESSAGES = require('../internal').MESSAGES
const _get = require('lodash/get')

/**
 * Plain consumer.
 * One plain consumers can listen to many plain producers.
 * Init example:
 * <pre>
 *     const iamqp              = require('iamqp');
 *     const amqpUri            = 'amqp://localhost';
 *     const channel            = 'amqp-channel-b';
 *     let plainConsumer        = new iamqp.PlainConsumer(amqpUri, channel);
 *
 *     // This needs to be done or the errors will bubble up.
 *     plainConsumer.getEventer().on('error', (err) => {
 *       console.log('consumer error:' + err.message);
 *     });
 *
 *     // For when the connection is established.
 *     plainConsumer.getEventer().on('connected', () => {
 *       console.log('consumer connected');
 *     });
 *
 *     // Get messages.
 *     plainConsumer.getEventer().on('message', (message) => {
 *       console.log('consumer message:' + message);
 *     });
 *
 *     // Open the connection - this takes some time and is not sync
 *     plainConsumer.openConnection();
 *
 *     // ...
 *
 *     // Close the connection
 *     if (plainConsumer.closeConnection()) {
 *       console.log('consumer connection closing ...');
 *     }
 * </pre>
 * ...
 */
class PlainConsumer extends require('../common') {
  /**
   * @param {AmqpURI} amqpUri
   * @param {ChannelName} channelName
   * @param {Configuration} [configuration]
   */
  constructor (amqpUri, channelName, configuration) {
    super(amqpUri, channelName, configuration)
    this._name = `PLAIN-CONSUMER: ${this._configuration.channelName}`
    this._messageDispatcherWrapper('info', MESSAGES.INIT)

    this._E.on('connected', () => {
      this._amqp.connection.createChannel((channelCreatingErr, channelCreated) => {
        if (channelCreatingErr) {
          this._emitAndDispatchError(`${MESSAGES.CHANNEL_ERROR} -> ${channelCreatingErr.message}`)
          return
        }

        this._messageDispatcherWrapper('info', `${MESSAGES.CHANNEL_READY} -> ${MESSAGES.QUEUE_ASSERTING} -> ${MESSAGES.CONSUMING}`)
        this._amqp.channel = channelCreated
        this._amqp.channel.assertQueue(this._configuration.channelName, {
          arguments: _get(this._configuration, 'configuration.queueArguments', {})
        })
        this._amqp.channel.consume(this._configuration.channelName, (data) => {
          this._logData(data.content, 'consume')
          this._amqp.channel.ack(data)
          this._E.emit('message', this._parseConsumedMessage(data))
        })
      })
    })
  }
}

module.exports = PlainConsumer