CodePark/ questions / Microservices, queues & events
START PRACTICINGPRACTICE
Backend question · NestJS › Microservices, queues & events

How do you create a Nest microservice and call it from another app using ClientProxy?

// math service
const app = await NestFactory.createMicroservice<MicroserviceOptions>(AppModule, {
  transport: Transport.TCP, options: { port: 4000 },
});
@MessagePattern({ cmd: "sum" })
sum(@Payload() nums: number[]) { return nums.reduce((a, b) => a + b, 0); }

// caller
ClientsModule.register([{ name: "MATH", transport: Transport.TCP, options: { port: 4000 } }]);
constructor(@Inject("MATH") private client: ClientProxy) {}
total = await firstValueFrom(this.client.send({ cmd: "sum" }, [1, 2, 3]));

Start the service with NestFactory.createMicroservice(). Call it from another app through a ClientProxy from ClientsModule.register().

The microservice side. createMicroservice() starts an app that listens on a transport instead of HTTP. A transport is the way messages travel. Built-in transports are TCP, Redis, NATS, MQTT, RabbitMQ, Kafka and gRPC. Handlers live in controllers. You decorate them with @MessagePattern() or @EventPattern(), and @Payload() reads the data.

The calling side. ClientsModule.register() creates a ClientProxy under an injection token.

  • client.send(pattern, data) returns an Observable of the response. It is cold: nothing is sent until you subscribe. You usually subscribe with firstValueFrom().
  • client.emit() publishes an event and doesn't wait for a reply.

An HTTP app can also host microservice listeners. Call app.connectMicroservice() and then app.startAllMicroservices(). This creates a hybrid application.

  • createMicroservice starts an app that listens on a transport.
  • Handlers use @MessagePattern or @EventPattern, with @Payload() for the data.
  • ClientsModule.register gives you a ClientProxy.
  • send() is cold, so you must subscribe or use firstValueFrom.
  • connectMicroservice creates a hybrid HTTP and microservice app.