Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion index.js
Original file line number Diff line number Diff line change
@@ -1 +1 @@
module.exports = require('./lib/rabbit');
module.exports = require('./lib/rabbit');
46 changes: 34 additions & 12 deletions lib/rabbit.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
const events = require('events'),
util = require('util'),
Transport = require('@mydevices/transporter').Transport;

const util = require('util');
const Transport = require('@mydevices/transporter').Transport;
const amqp = require('amqplib');

//
Expand All @@ -12,13 +11,15 @@ const amqp = require('amqplib');
//
const Rabbit = function (options) {
Transport.call(this, options);
this.options = options || {

this.options = Object.assign({
uri: 'amqp://localhost',
exchange: 'rabbit-transporter-exchange',
type: 'fanout'
};
type: 'fanout'
}, options);

this.channel = null;
this.failed = false;
const self = this;

amqp.connect(this.options.uri, { rejectUnauthorized: false })
Expand All @@ -27,11 +28,24 @@ const Rabbit = function (options) {
})
.then((ch) => {
self.channel = ch;

ch.on('error', (err) => {
self.failed = true;
self.emit('error', err, self);
});
ch.on('close', () => {
self.failed = true;
self.emit('error', new Error('AMQP channel closed'), self);
});

return ch.assertExchange(self.options.exchange, self.options.type);
})
.then(console.log)
.catch(console.warn);

.then(msg => self.emit('ready', msg))
.catch(err => {
self.emit('error', err, self);
self.failed = true;
return;
});
};

//
Expand All @@ -45,9 +59,17 @@ util.inherits(Rabbit, Transport);
Rabbit.prototype.name = 'Rabbit';

Rabbit.prototype.publish = function(msg, callback) {
const self = this;
self.channel.publish(self.options.exchange, msg.bus, Buffer.from(JSON.stringify(msg)));
if (this.failed) {
this.emit('error', new Error('AMQP connection error'), this);
return callback();
} else if (this.channel) {
// catch a closed channel, let listener emit the event
try {
this.channel.publish(this.options.exchange, msg.bus, Buffer.from(JSON.stringify(msg)));
} catch (error) {}
}

return callback(null);
}

exports.Rabbit = Rabbit;
exports.Rabbit = Rabbit;