From b325500310da00a827baea406cbff8192a682fb7 Mon Sep 17 00:00:00 2001 From: luissantosjs Date: Tue, 26 Aug 2025 19:15:59 +0100 Subject: [PATCH] improve rabbit controller --- .../event/rabbitmq/rabbitmq.controller.ts | 34 +++++++++++++++---- 1 file changed, 27 insertions(+), 7 deletions(-) diff --git a/src/api/integrations/event/rabbitmq/rabbitmq.controller.ts b/src/api/integrations/event/rabbitmq/rabbitmq.controller.ts index 24468ac8..3295b12d 100644 --- a/src/api/integrations/event/rabbitmq/rabbitmq.controller.ts +++ b/src/api/integrations/event/rabbitmq/rabbitmq.controller.ts @@ -45,7 +45,7 @@ export class RabbitmqController extends EventController implements EventControll heartbeat: 30, // Add heartbeat of 30 seconds }; - amqp.connect(connectionOptions, (error, connection) => { + amqp.connect(connectionOptions, (error: Error, connection: amqp.Connection) => { if (error) { this.logger.error({ local: 'RabbitmqController.connect', @@ -57,7 +57,7 @@ export class RabbitmqController extends EventController implements EventControll } // Connection event handlers - connection.on('error', (err) => { + connection.on('error', (err: Error) => { this.logger.error({ local: 'RabbitmqController.connectionError', message: 'RabbitMQ connection error', @@ -71,7 +71,7 @@ export class RabbitmqController extends EventController implements EventControll this.handleConnectionLoss(); }); - connection.createChannel((channelError, channel) => { + connection.createChannel((channelError: Error, channel: amqp.Channel) => { if (channelError) { this.logger.error({ local: 'RabbitmqController.createChannel', @@ -83,7 +83,7 @@ export class RabbitmqController extends EventController implements EventControll } // Channel event handlers - channel.on('error', (err) => { + channel.on('error', (err: Error) => { this.logger.error({ local: 'RabbitmqController.channelError', message: 'RabbitMQ channel error', @@ -136,8 +136,7 @@ export class RabbitmqController extends EventController implements EventControll return; // Already attempting to reconnect } - this.amqpChannel = null; - this.amqpConnection = null; + this.cleanup(); this.scheduleReconnect(); } @@ -406,4 +405,25 @@ export class RabbitmqController extends EventController implements EventControll } } } -} \ No newline at end of file + + public async cleanup(): Promise { + try { + if (this.amqpChannel) { + await this.amqpChannel.close(); + this.amqpChannel = null; + } + if (this.amqpConnection) { + await this.amqpConnection.close(); + this.amqpConnection = null; + } + } catch (error) { + this.logger.warn({ + local: 'RabbitmqController.cleanup', + message: 'Error during cleanup', + error: error.message || error, + }); + this.amqpChannel = null; + this.amqpConnection = null; + } + } +}