84 lines
2.0 KiB
TypeScript
84 lines
2.0 KiB
TypeScript
import client, { ChannelModel, ConfirmChannel, connect, Connection } from "amqplib"
|
|
import { env } from "config/env"
|
|
|
|
const rmqUser = env.RABBITMQ_USER
|
|
const rmqPass = env.RABBITMQ_PASSWORD
|
|
const rmqHost = env.RABBITMQ_HOST
|
|
const rmqPort = Number(env.RABBITMQ_PORT)
|
|
const rmqSecure = false
|
|
const rmqVhost = env.RABBITMQ_VHOST
|
|
|
|
|
|
const PREFETCH_LIMIT = 1
|
|
|
|
class RabbitConnection {
|
|
connection?: ChannelModel
|
|
channel?: ConfirmChannel
|
|
connected: Boolean = false
|
|
|
|
public async connect() {
|
|
this.connection = await this.createConnection();
|
|
if (this.connection == undefined) throw new Error("[RMQ] Error crecreando la conexion")
|
|
this.channel = await this.createConfirmChannel()
|
|
}
|
|
|
|
protected async createConnection() {
|
|
const { hostname, port, secure } = { hostname: rmqHost, port: rmqPort, secure: rmqSecure }
|
|
const { username, password } = { username: rmqUser, password: rmqPass };
|
|
const protocol = secure ? 'amqps' : 'amqp';
|
|
const vhost = rmqVhost
|
|
|
|
const connection = await client.connect({
|
|
protocol,
|
|
hostname,
|
|
port,
|
|
username,
|
|
password,
|
|
vhost
|
|
});
|
|
|
|
connection.on('error', (error: unknown) => {
|
|
console.error(`[RMQ] Rabbitmq connection error :: ${error}`);
|
|
Promise.reject(error);
|
|
});
|
|
|
|
return connection;
|
|
}
|
|
|
|
protected async createConfirmChannel() {
|
|
const channel = await this.connection?.createConfirmChannel()
|
|
await channel?.prefetch(PREFETCH_LIMIT)
|
|
|
|
if (channel == undefined) throw new Error("[RMQ] Error crecreando el canal")
|
|
|
|
channel.on('error', (error: unknown) => {
|
|
console.error(`[RMQ] Rabbitmq channel error :: ${error}`);
|
|
Promise.reject(error);
|
|
});
|
|
|
|
return channel;
|
|
|
|
}
|
|
}
|
|
|
|
async function test() {
|
|
const rbmq = new RabbitConnection()
|
|
await rbmq.connect()
|
|
|
|
console.log("enviando")
|
|
|
|
rbmq.channel?.sendToQueue("sim.queue", Buffer.from("test"), {},
|
|
function (err, ok) {
|
|
if (err !== null)
|
|
console.warn('Message nacked!');
|
|
else
|
|
console.log('Message acked');
|
|
}
|
|
)
|
|
|
|
}
|
|
|
|
test()
|
|
|
|
export default {}
|