Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
getConnection() {
const url = this._config.host;
const { hostname } = this._config;
let connection = this.connections[url];
// cache handling, if connection already opened, return it
if (connection && connection.conn) {
return Promise.resolve(connection.conn);
}
// prepare the connection internal object, and reset channel if connection has been closed
this.connections[url] = {
conn: null,
channel: null
};
connection = this.connections[url];
connection.conn = amqp.connect(url, {
clientProperties: {
hostname,
bunnymq: packageVersion,
startedAt: this.startedAt,
connectedAt: new Date().toISOString()
}
}).then((conn) => {
// on connection close, delete connection
conn.on('close', () => {
delete connection.conn;
});
conn.on('error', this._config.transport.error);
connection.conn = conn;
return conn;
}).catch((e) => {
connection.conn = null;
private async createConnection(): Promise {
if (MQProvider.enabled) {
const { url } = MQConfigObject.load();
logger.log(`connecting to ${url}`);
const connection = await amqp.connect(url).catch(error => logger.error(`connect to mq error: ${r(error)}`));
if (connection == null) {
if (this._retryLimit < 1) {
process.exit(1);
}
setTimeout(
() =>
this.createConnection().catch(() => {
this._retryLimit -= 1;
logger.error(`reconnect(${10 - this._retryLimit}) to mq error, retry in 10s.`);
}),
10000,
);
return Promise.reject();
}
initialize() {
return amqp
.connect('amqp://localhost')
.then(conn => conn.createChannel())
.then(channel => {
this.channel = channel;
return channel.assertQueue('', {exclusive: true});
})
.then(q => {
this.replyQueue = q.queue;
return this._listenForResponses();
})
.catch(function(err) {
console.log(err);
})
;
}
async init(): Promise {
try {
this.connection = await connect(environment.rabbitMQ.amqpUrl);
this.channel = await this.connection.createChannel();
for (const queueType in QueueType) {
if (QueueType.hasOwnProperty(queueType) && queueType) {
await this.channel.assertQueue(QueueType[queueType], { durable: true });
}
}
} catch (error) {
const errorMessage = `Error connecting or creating channels on RabbitMQ`;
logger.error(errorMessage, [error]);
throw new Error(error);
}
}
#!/usr/bin/env node
var amqp = require('amqplib');
amqp.connect('amqp://localhost').then(function(conn) {
process.once('SIGINT', function() { conn.close(); });
return conn.createChannel().then(function(ch) {
var ok = ch.assertExchange('logs', 'fanout', {durable: false});
ok = ok.then(function() {
return ch.assertQueue('', {exclusive: true});
});
ok = ok.then(function(qok) {
return ch.bindQueue(qok.queue, 'logs', '').then(function() {
return qok.queue;
});
});
ok = ok.then(function(queue) {
return ch.consume(queue, logMessage, {noAck: true});
});
return ok.then(function() {
console.log(' [*] Waiting for logs. To exit press CTRL+C');
const con = {
protocol: 'amqp',
hostname: host,
port: port,
username: username,
password: password,
locale: 'en_US',
frameMax: 0,
heartbeat: 0,
vhost: '/',
routing_key: routingKey,
exchange: exchange,
mq_type: type,
durable: durable,
};
const clientconn = amqplib.connect(con);
clientconn.publish = amqplib.connect(con).publish ? amqplib.connect(con).publish : (client, message) => {
client.then((conn) => {
const rn = conn.createChannel().then((ch) => {
const ok = ch.assertExchange(exchange, type, { durable: durable });
return ok.then(() => {
ch.publish(exchange, routingKey, Buffer.from(message));
return ch.close();
});
});
return rn;
}).catch(console.error);
};
function log(loggingEvent) {
const message = layout(loggingEvent);
clientconn.publish(clientconn, message);
}
constructor({ host, port, user, pass }) {
this.connection = amqplib.connect({
protocol: 'amqp',
hostname: host,
port: port,
username: user,
password: pass,
heartbeat: 30,
});
}
export async function postTransactionToLedger(transaction) {
if (transaction.deletedAt || transaction.type !== 'CREDIT') {
return Promise.resolve();
}
try {
const ledgerTransaction = await getTransactionWithNestedProperties(transaction);
if (!process.env.QUEUE_ENABLED) {
return axios.post(ledger.transactionUrl, ledgerTransaction);
}
const conn = await amqp.connect(ledgerQueue.url);
const channel = await conn.createChannel();
await channel.assertQueue(ledgerQueue.transactionQueue, { exclusive: false });
channel.sendToQueue(ledgerQueue.transactionQueue, Buffer.from(JSON.stringify([ledgerTransaction]), 'utf8'));
} catch (error) {
debug('postTransactionToLedger error', error);
}
}
export function connect() {
if (!amqpConnectionPromise) {
amqpConnectionPromise = amqp.connect(config.get('amqp.url'))
}
return amqpConnectionPromise
}
Module.connect = (options) => {
const { host, context } = options;
if (channels[host] && channels[host][context]) {
return new Promise(resolve => resolve(channels[host][context]));
}
return amqp.connect(host)
.then(connection => connection.createConfirmChannel())
.then((channel) => {
channels[host] = channel[host] ? channels[host] : {};
channels[host][context] = channel;
return channels[host][context];
})
.catch((error) => {
helpers.log('error', error.message, options);
return error;
});
};