Adrian Thompson
Adrian Thompson

Reputation: 71

Problems with RabbitMQ and NestJS. I can't publish a message with nestjs-rabbitmq and NestJS

I have NestJS 8.0.0 and I'm using @golevelup/nestjs-rabbitmq": "2.2.0. Basically I have handling messages working fine but I can't send any, I just get a "Cannot read properties of undefined (reading 'isConnected')" error.

I'm following this approach:

https://www.npmjs.com/package/@golevelup/nestjs-rabbitmq#publising-messages-fire-and-forget

This is from a controller which I'm trying to send a message from. I've injected in the AmqpConnection as per instructions

constructor(private readonly amqpConnection: AmqpConnection) {}

await this.amqpConnection.publish(
      // exchange name defined by other service which have subscriber
      'my.exchange.name',
      // routing key
      'my.routing.key',
      queueMessage
    );

The error I'm getting is:

"TypeError: Cannot read properties of undefined (reading 'isConnected')\n    at AmqpConnection.publish (LOCAL_PATH\\node_modules\\@golevelup\\nestjs-rabbitmq\\src\\amqp\\connection.ts:423:33)\n    at MessageController.handleMessage 
"Cannot read properties of undefined (reading 'isConnected')"

My assumption is that I've done something stupid with the setup. This is backed up by the fact that the app loads correctly and spits out all the correct console messages: Successfully connected to a RabbitMQ broker Initializing RabbitMQ Handlers Successfully connected a RabbitMQ channel "AmqpConnection" etc etc

Any help much appreciated!

Upvotes: 0

Views: 9556

Answers (1)

Adrian Thompson
Adrian Thompson

Reputation: 71

I fixed this issue. It was related to the way I had set up NestJS. I was not exporting the RabbitMQModule in the rabbit.module.ts I had created. Now my module looks like this:

@Global()
@Module({
  controllers: [],
  imports: [
    RabbitMQModule.forRoot(RabbitMQModule, {
      exchanges: [
        {
          name: 'exchange-name',
          type: 'topic',
        },
      ],
      uri: 'amqps://rabbitmqservice',
      connectionInitOptions: { wait: false },
      enableControllerDiscovery: true
    }),
    RabbitModule
  ],
  providers: [],
  exports: [RabbitMQModule]
})
export class RabbitModule {}

And works fine when injecting the connection into the constructor of my controller as per instructions:

constructor(
    private readonly amqpConnection: AmqpConnection
  ) {}

Upvotes: 4

Related Questions