I would like to build a common helper for my application that will manage all the amqplib calls from all of my nodeJS microservices.
I would like to import my amqplibHelper to every microservice and use only my helper commands that they will call internally to the amqplib node.js library so I will be able to use different library in the future of to make changes regarding the amqp commands more easily in one central place.
I created a new npm package for that and tried to write something from scratch but since I don't have too much experience in amqp. I am looking for a "bootstrap" or a template as starting point.
I started with this but I feel I am not going in the right way.
class commonAmqp {
amqp = require('amqplib');
connection = start();
constructor(rabbitmqClientm, validQueues) {
this.rabbitmqClient = rabbitmqClient;
this.validQueues = validQueues;
const { queuesLocal, queuesRemote } = rabbitmqClient;
const isLocal = queuesLocal.includes(queue);
const isRemote = queuesRemote.includes(queue);
}
async initQueue(queue, data) {
if (!validQueues.includes(queue)) throw HttpError(g.f('Not valid queue'));
const { connection, queue } = this;
const valid = queueValidator(queue, data);
const channel = connection.then(conn => (conn.createChannel()));
if (!channel || !valid)
throw new Error('Not valid queue || queue-data');
channel.then(function(ch) {
return ch.assertQueue(queue).then(function(ok) {
return ch.sendToQueue(queue, new Buffer.from(JSON.stringify(data)));
});
});
};
async start() {
const connection = await this.amqp.connect(rabbitmqClient.url);
console.log('Connected to RabbitMQ-server');
connection.on('error', (err) => {
console.log('rabbitmq-err', err);
setTimeout(start, 2000);
});
connection.on('close', () => {
console.log('rabbitmq-connection closed');
setTimeout(start, 5000);
});
return connection;
}
config(config) {
this.config = config;
console.log('config: ' + this.config);
}
}
module.exports = {
commonAmqp
};