Message patterns let parts of your app talk by sending and answering messages. This helps organize code and handle tasks step-by-step.
0
0
Message patterns (request-response) in NestJS
Introduction
When you want one part of your app to ask another part for data or action and wait for the answer.
When building microservices that communicate by sending messages.
When you want to separate concerns by handling requests in dedicated handlers.
When you need to process commands or queries asynchronously but still get a response.
When you want to use NestJS built-in support for message-based communication.
Syntax
NestJS
import { Controller } from '@nestjs/common'; import { MessagePattern } from '@nestjs/microservices'; @Controller() export class MyController { @MessagePattern('pattern_name') handleMessage(data: any) { // process data const response = {}; // define response return response; } }
The @MessagePattern decorator marks a method to listen for messages matching the given pattern.
The method should return a value or a Promise that will be sent back as the response.
Examples
This listens for messages with pattern 'sum' and returns the sum of two numbers.
NestJS
import { Controller } from '@nestjs/common'; import { MessagePattern } from '@nestjs/microservices'; @Controller() export class MathController { @MessagePattern('sum') sumNumbers(data: {a: number, b: number}) { return data.a + data.b; } }
This listens for 'greet' messages and returns a greeting string.
NestJS
import { Controller } from '@nestjs/common'; import { MessagePattern } from '@nestjs/microservices'; @Controller() export class GreetingController { @MessagePattern('greet') greet(name: string) { return `Hello, ${name}!`; } }
Sample Program
This controller listens for messages with the pattern 'multiply'. When it receives data with numbers x and y, it returns their product.
NestJS
import { Controller } from '@nestjs/common'; import { MessagePattern } from '@nestjs/microservices'; @Controller() export class CalculatorController { @MessagePattern('multiply') multiplyNumbers(data: {x: number, y: number}) { return data.x * data.y; } }
OutputSuccess
Important Notes
Message patterns can be strings or objects to better organize message types.
Handlers can return synchronous values or Promises for async processing.
Use NestJS microservices package to enable message-based communication.
Summary
Message patterns help parts of your app communicate by sending and receiving messages.
Use @MessagePattern to listen for specific message types.
Handlers return responses that go back to the sender.