0

I'm new to @nestjs/microservices, and running into a weird issue.

I have a setup of two apps written in Nest and checking the micro-service connection between them. For some strange reason, clientProxy.emit / @EventPattern works - but clientProxy.send / @MessagePattern is not. I've double checked the connection, it works fine. But the request/response approach does not work for me.

Any help would be greatly appreciated.. Sending the request is as follows:

this.shortenerService
      .send('create', {
        url: 'test',
      });

client code

Receiving:

  @UsePipes(new ValidationPipe())
  @MessagePattern('create')
  async create(@Payload() data: CreateDto): Promise<string> {
    return Promise.resolve(`${Math.random()}`);
  }

server code

Tried to change to .emit in client and @EventPattern in server - and it works. But not for request/response.

Tried to organize into a minimal repository

1 Answers1

2

Nest's microservice ClientProxy uses observables, and send are cold observables, so you need to either return the response of .send for Nest to later subscribe, use .subscribe() yourself to kick off the observable, or convert the observable to a promise using lastValueFrom so you can await the response

Jay McDoniel
  • 57,339
  • 7
  • 135
  • 147
  • Thanks @jay-mcdoniel... Yes, the actual code is a bit different - but the call is not received by the 'server' (looking at the log), when it's request/response - but works fine with 'emit' – Alex Postnikov Aug 15 '23 at 17:47
  • Right, because [as the docs mention](https://docs.nestjs.com/microservices/basics#publishing-events) `.emit` is a "hot" observable, meaning it doesn't need to be subscribed to – Jay McDoniel Aug 15 '23 at 17:55
  • Wow, thanks.. Due to optimization, even .toPromise() was not actually executed, needed to subscribe / use 'lastValueFrom' to get the call run. Thanks a lot! – Alex Postnikov Aug 15 '23 at 18:37