iamqp
Version:
RabbitMQ wrapper for NodeJS with several produce(reply)/consume scenarios
83 lines (77 loc) • 2.71 kB
JavaScript
const MESSAGES = require('../internal').MESSAGES
const _get = require('lodash/get')
const _isNull = require('lodash/isNull')
/**
* Plain producer.
* Multiple plain producers can publish to a single plain consumer.
* Init example:
* <pre>
* const iamqp = require('iamqp');
* const amqpUri = 'amqp://localhost';
* const channel = 'amqp-channel-b';
* let plainProducer = new iamqp.PlainProducer(amqpUri, channel);
*
* // This needs to be done or the errors will bubble up.
* plainProducer.getEventer().on('error', (err) => {
* console.log('producer error:' + err.message);
* });
*
* // For when the connection is established.
* plainProducer.getEventer().on('connected', () => {
* console.log('producer connected');
* });
*
* // Open the connection - this takes some time and is not sync
* plainProducer.openConnection();
*
* // Publish a single message.
* let isPublishing = plainProducer.publish({
* 'a': 3
* });
*
* // Close the connection
* if (plainProducer.closeConnection()) {
* console.log('producer connection closing ...');
* }
* </pre>
* ...
*/
class PlainProducer extends require('../common') {
/**
* @param {AmqpURI} amqpUri
* @param {ChannelName} channelName
* @param {Configuration} [configuration]
*/
constructor (amqpUri, channelName, configuration) {
super(amqpUri, channelName, configuration)
this._name = `PLAIN-PRODUCER: ${this._configuration.channelName}`
this._messageDispatcherWrapper('info', 'init')
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)
this._amqp.channel = channelCreated
this._amqp.channel.assertQueue(this._configuration.channelName, {
arguments: _get(this._configuration, 'configuration.queueArguments', {})
})
}
})
})
}
/**
* Publish a message.
* @param {number | string | boolean | Object | Array} contentToPublish
* @returns {boolean}
*/
publish (contentToPublish) {
const data = this._commonPublishPreparations(contentToPublish)
if (!_isNull(data)) {
this._amqp.channel.sendToQueue(this._configuration.channelName, data)
return true
}
return false
}
}
module.exports = PlainProducer