Eran Abir
Eran Abir

Reputation: 1097

Nest.js RabbitMQ not sending/receiving message

I have two microservices with Nest.js both of them connected to RabbitMQ service (one is the publisher and one is the receiver) From the publisher I am trying to send a message to the receiver and seems that its not doing anything at all

Publisher :

auth.module.ts :
 imports:[ClientsModule.registerAsync([
      {
        name: 'RMQ_SERVICE',
        imports: [ConfigModule],
        useFactory: (configService: ConfigService) => ({
          transport: Transport.RMQ,
          options: {
            urls: [`amqp://${configService.get('RMQ_HOST')}:5672`],
            queue: 'api-queue',
            queueOptions: {
              durable: false,
            },
          },
        }),
        inject: [ConfigService],
      },
    ]),
]

auth.service.ts : 
@Inject('RMQ_SERVICE') private readonly client: ClientProxy,

and using it like that : 
 this.client.send({ cmd: 'create-user-data' },{});

Receiver :

main.ts : 
app.connectMicroservice<MicroserviceOptions>({
    transport: Transport.RMQ,
    options: {
      noAck: false,
      urls: [`amqp://${process.env.RMQ_HOST}:5672`],
      queue: 'api-queue',
      queueOptions: {
        durable: false,
      },
    },
  });
  await app.startAllMicroservices();

users-data.controler.ts : 
  @MessagePattern({ cmd: 'create-user-data'})
  async createUserData() {
    console.log('create-user-data');
  }

cant see any errors also i have rabbitmq web monitor and cannot see there any messages

any idea what wrong ?

if ill use emit and EventPattern its working i dont understand why ?

Upvotes: 4

Views: 5807

Answers (2)

Ahmed Saber
Ahmed Saber

Reputation: 89

I will share my rabbitmq.service.ts with you can use it to send a message to the queue with the event name and your payload in my service I'm using lastValueFrom to convert from observer to promise too.

import { Inject, Injectable, Logger } from '@nestjs/common';
import { lastValueFrom } from 'rxjs';
import { ClientProxy } from '@nestjs/microservices';

@Injectable()
export class RabbitMQService {
  private readonly logger = new Logger(RabbitMQService.name);
  constructor(
    @Inject("queue-name")
    private readonly recurringClient: ClientProxy,
  ) {}
  async sendMessage(eventName: any, payload: object) {
    try {
      await lastValueFrom(this.recurringClient.emit(eventName, payload));
    } catch (error) {
      this.logger.error(
        `Problem with RMQ in ${eventName} error: ${JSON.stringify(error)}`,
      );
    }
  }
}

Upvotes: 0

Eran Abir
Eran Abir

Reputation: 1097

ok so after long digging i just needed to do

const result = await this.client.send(
        { cmd: 'create-user-data' },
        {
          userId: user.id,
          provider,
          ...socialUser,
        },
      );
      await result.subscribe();

and i received the message on the receiver

Upvotes: 5

Related Questions