How to get EventPattern working in Nest JS

时间:2019-04-17 01:00:45

标签: nestjs

I am setting up basic EventPattern between two NestJS instances. However the Event is not being emitted/received by the other Microservice.

I have tried to find some concrete examples on the docs, however it looks the setup is different than calling clinet.emit/client.call to invoke other microservices.

Microservice 1.

import { Controller, Get } from '@nestjs/common';
import { AppService } from './app.service';
import { Client, Transport, ClientProxy, ClientsModule, EventPattern } from '@nestjs/microservices';
import { Observable } from 'rxjs';


@Controller()
export class AppController {
  constructor(private readonly appService: AppService) {}

  @Client({ transport: Transport.REDIS })
  client: ClientProxy;

  @Get()
  async call(): Promise<number> {
    const pattern = { cmd: 'sum' };
    const payload = [1, 2, 3];
    const result = await this.client.emit('user_created', {age: 5});
    return this.client.send<number>(pattern, payload).toPromise();
  }


}

Microservice two

import { Controller } from '@nestjs/common';
import { MessagePattern, EventPattern, Client, Transport, ClientProxy } from '@nestjs/microservices';

@Controller()
export class MathController {

  @Client({ transport: Transport.REDIS })
  client: ClientProxy;

  @MessagePattern({ cmd: 'sum' })
  sum(data: number[]): number {
    console.log('Message');
    return 1;
  }

  @EventPattern('user_created')
  async handleUserCreated(data: Record<string, unknown>) {
    console.log('EVENT');
    // business logic
  }
}

When we call Microservice1.get the client the call to sum does occur and Message is printed on Microservice 2. However the expectation is that EVENT is printed on Microservice 2 too.

1 个答案:

答案 0 :(得分:1)

在测试框架时,我遇到了同样的问题,并且通过在toPromise()调用中添加emit得到了预期的结果。

因此您可以尝试:

const result = await this.client.emit('user_created', {age: 5});.toPromise()

emit返回一个可观察的对象,因此您必须订阅它。 toPromise()subscribe()都可以。

有关更多信息:https://www.learnrxjs.io/concepts/rxjs-primer.html