Consider this NestJS microservice handler using a message pattern. What will be the response when the client sends a message with pattern 'sum' and data {a: 3, b: 4}?
import { Controller } from '@nestjs/common'; import { MessagePattern } from '@nestjs/microservices'; @Controller() export class MathController { @MessagePattern('sum') sum(data: { a: number; b: number }) { return data.a + data.b; } }
Think about what the handler returns when it receives the data.
The handler receives an object with properties a and b. It returns their sum, so 3 + 4 = 7.
Choose the correct syntax to define a message pattern handler that listens for the pattern 'get_user'.
Remember the decorator syntax requires parentheses and a string argument.
Option D uses the correct decorator syntax with parentheses and a string pattern. Other options have syntax errors.
Given this code, why does the microservice never respond to messages with pattern 'ping'?
import { Controller } from '@nestjs/common'; import { MessagePattern } from '@nestjs/microservices'; @Controller() export class PingController { @MessagePattern('ping') ping() { console.log('Ping received'); } }
Think about what happens if a handler does not return a response.
The handler logs the message but does not return anything. In request-response, the client expects a response, so it waits forever.
Consider this NestJS microservice controller that counts how many times it received a 'count' message. What is the value of count after processing three messages with pattern 'count'?
import { Controller } from '@nestjs/common'; import { MessagePattern } from '@nestjs/microservices'; @Controller() export class CounterController { private count = 0; @MessagePattern('count') increment() { this.count++; return this.count; } }
Each message triggers the increment method once.
The count starts at 0 and increments by 1 for each message. After 3 messages, it becomes 3.
Choose the correct statement about how NestJS handles request-response message patterns in microservices.
Think about how request-response communication works in microservices.
In NestJS, to send a response back to the client, the handler must return a value or a Promise. Otherwise, the client waits indefinitely.