I started working with NestJs recently and got stock while trying to test my NestJs microservices app using a TCP client

Is it possible to trigger an @EventPattern or @MessagePattern() using a non-nest app?

When trying this method the the socket client just stuck on trying to connect.

Any ideas?


1 Answers

Kim Kern On Best Solutions

You have to setup the ports correctly to use it with nest:

The pattern you want to send is

<json-length>#{"pattern": <pattern-name>, "data": <your-data>[, "id": <message-id>]}



The parameter id is for @MessagePattern, without it @EventPattern will be triggered.

enter image description here

In your main.ts you setup the nest server. That's the port you want to send to from Packet Sender (enter at 1).

const app = await NestFactory.createMicroservice(AppModule, {
  transport: Transport.TCP,
  options: { host: 'localhost', port: 3005 },
  //                            ^^^^^^^^^^

Then you want your nest @Client to listen to messages coming from Packet Sender (see position 2 in image)

  transport: Transport.TCP,
  options: { host: 'localhost', port: 52079 },
  //                            ^^^^^^^^^^^  
private client: ClientTCP;

Then connect your client:

async onModuleInit() {
  await this.client.connect();

and define a @MessagePattern:

sum(data: number[]): number {
  return data.reduce((a, b) => a + b, 0);

As you can see, in the example I'm sending [0,3,3] and nest correctly responds with the sum 6.