Message patterns let parts of your app talk by sending and answering messages. This helps organize code and handle tasks step-by-step.
Message patterns (request-response) in 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.
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; } }
import { Controller } from '@nestjs/common'; import { MessagePattern } from '@nestjs/microservices'; @Controller() export class GreetingController { @MessagePattern('greet') greet(name: string) { return `Hello, ${name}!`; } }
This controller listens for messages with the pattern 'multiply'. When it receives data with numbers x and y, it returns their product.
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; } }
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.
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.
Practice
@MessagePattern decorator in NestJS?Solution
Step 1: Understand the role of
This decorator is used to mark a method that listens for messages matching a specific pattern.@MessagePatternStep 2: Differentiate from other decorators
Unlike HTTP route decorators,@MessagePatternis for message-based communication, not HTTP or database setup.Final Answer:
To listen for specific message types and handle incoming messages -> Option BQuick Check:
@MessagePatternlistens for messages [OK]
@MessagePattern listens, not sends [OK]- Confusing
@MessagePatternwith HTTP route decorators - Thinking it sends messages instead of listening
- Assuming it configures databases
Solution
Step 1: Identify the correct decorator for message patterns
@MessagePatternis the correct decorator to listen for messages, not@Get,@Post, or@Subscribe.Step 2: Confirm the syntax
The pattern string 'sum_numbers' is correctly passed as an argument to@MessagePattern, and the handler method processes the data.Final Answer:
@MessagePattern('sum_numbers') handleSum(data: number[]) { return data.reduce((a, b) => a + b); } -> Option DQuick Check:
Use@MessagePattern('pattern')for message handlers [OK]
@MessagePattern for message handlers, not HTTP decorators [OK]- Using HTTP decorators like
@Getor@Postfor message patterns - Using non-existent decorators like
@Subscribe - Forgetting to pass the pattern string to
@MessagePattern
@MessagePattern('multiply')
handleMultiply(data: number[]) {
return data[0] * data[1];
}Solution
Step 1: Understand the handler logic
The handler receives an array of numbers and returns the product of the first two elements: data[0] * data[1].Step 2: Calculate the product for input [2, 3]
2 * 3 equals 6, so the response will be 6.Final Answer:
6 -> Option AQuick Check:
2 multiplied by 3 equals 6 [OK]
- Adding instead of multiplying the numbers
- Returning the input array instead of the product
- Assuming undefined because of missing return
@MessagePattern('greet')
async handleGreet(name: string) {
console.log('Greeting:', name);
}Solution
Step 1: Check the handler's return behavior
The handler logs the name but does not return any value, so the sender gets no response.Step 2: Verify decorator and parameter correctness
The decorator has the pattern string 'greet', and the parameter type string is acceptable for simple messages.Final Answer:
The handler does not return a response to the sender -> Option CQuick Check:
Handlers must return a response [OK]
- Not returning a response causes sender to wait indefinitely
- Confusing async usage with missing return
- Assuming parameter type must be object always
{ a: 5, b: 7 }. Which of the following handler implementations correctly achieves this?Solution
Step 1: Match the expected input structure
The message sends an object with propertiesaandb, so the handler must accept an object with those properties.Step 2: Verify the handler logic
The handler correctly accessesdata.aanddata.band returns their sum.Step 3: Check other options for correctness
@MessagePattern('calculate') handleCalculate(a: number, b: number) { return a + b; } expects two separate parameters, which does not match the single object sent. @MessagePattern('calculate') handleCalculate(data: number[]) { return data[0] + data[1]; } expects an array, and @MessagePattern('calculate') handleCalculate(data: string) { return parseInt(data); } expects a string, both incorrect.Final Answer:
@MessagePattern('calculate') handleCalculate(data: { a: number; b: number }) { return data.a + data.b; } -> Option AQuick Check:
Match input shape and sum properties [OK]
- Using multiple parameters instead of one object
- Expecting array when object is sent
- Parsing string instead of object
Ready to prove it?
Pass the test and this pattern moves unknown
