UNPKG

iamqp

Version:

RabbitMQ wrapper for NodeJS with several produce(reply)/consume scenarios

87 lines (81 loc) 2.87 kB
const MESSAGES = require('../internal').MESSAGES const _isNull = require('lodash/isNull') /** * Create a producer for an exchange of the fanout type. * Multiple fanout producers can fanout to multiple fanout consumers. * Init example: * <pre> * const iamqp = require('iamqp'); * const amqpUri = 'amqp://localhost'; * const fanoutChannel = 'fanout-channel-a'; * let fanoutProducer = new iamqp.FanoutProducer(amqpUri, fanoutChannel); * * // This needs to be done or the errors will bubble up. * fanoutProducer.getEventer().on('error', (err) => { * console.log('fanout producer error:' + err.message); * }); * * // For when the connection is established. * fanoutProducer.getEventer().on('connected', () => { * console.log('fanout producer connected'); * }); * * // Open the connection - this takes some time and is not sync * fanoutProducer.openConnection(); * * // ... * * // Fanout a single message. * let isFanout = fanoutProducer.fanout({ * 'a': 3 * }); * * // ... * * // Close the connection * if (fanoutProducer.closeConnection()) { * console.log('fanout producer connection closing ...'); * } * </pre> * ... */ class FanoutProducer extends require('../common') { /** * @param {AmqpURI} amqpUri * @param {ChannelName} channelName * @param {Configuration} [configuration] */ constructor (amqpUri, channelName, configuration) { super(amqpUri, channelName, configuration) this._name = `FANOUT-PRODUCER: ${this._configuration.channelName}` this._messageDispatcherWrapper('info', MESSAGES.INIT) // Comes from the common class where the connection occurs this._E.on('connected', () => { this._amqp.connection.createChannel((channelCreatingErr, channelCreated) => { if (channelCreatingErr) { this._emitAndDispatchError(`${MESSAGES.CHANNEL_ERROR} -> ${channelCreatingErr.message}`) } else { this._messageDispatcherWrapper('info', `${MESSAGES.CHANNEL_READY} -> ${MESSAGES.EXCHANGE_ASSERTING} -> ${MESSAGES.FANOUT}`) this._amqp.channel = channelCreated this._amqp.channel.assertExchange(this._configuration.channelName, 'fanout', { durable: false }) } }) }) } /** * Fanout a message. * @param {number | string | boolean | Object | Array} contentToPublish * @returns {boolean} */ fanout (contentToPublish) { const data = this._commonPublishPreparations(contentToPublish) if (!_isNull(data)) { this._amqp.channel.publish(this._configuration.channelName, '', data) return true } return false } } module.exports = FanoutProducer