Message patterns implement request-response communication between Nest microservices. This lesson covers @MessagePattern handlers and ClientProxy.send().
Request-Response With @MessagePattern
A consumer decorates a method with @MessagePattern({ cmd: 'sum' }). A producer calls client.send({ cmd: 'sum' }, payload) and receives an Observable/Promise reply. This is Nest's RPC style over the configured transporter.
@Controller()
export class MathController {
@MessagePattern({ cmd: 'sum' })
sum(data: number[]): number {
return data.reduce((a, b) => a + b, 0);
}
}
The pattern object { cmd: 'sum' } must match exactly between sender and receiver.