Bird
Raised Fist0
NestJSframework~20 mins

Message patterns (request-response) in NestJS - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
NestJS Message Patterns Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ component_behavior
intermediate
2:00remaining
What is the output of this NestJS microservice handler?

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}?

NestJS
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;
  }
}
A7
Bundefined
CThrows an error
DNaN
Attempts:
2 left
💡 Hint

Think about what the handler returns when it receives the data.

📝 Syntax
intermediate
2:00remaining
Which option correctly defines a message pattern handler in NestJS?

Choose the correct syntax to define a message pattern handler that listens for the pattern 'get_user'.

A
@MessagePattern('get_user')
getUser(data) => {
  return data;
}
B
@MessagePattern get_user
getUser(data) {
  return data;
}
C
@MessagePattern('get_user')
getUser {
  return data;
}
D
@MessagePattern('get_user')
getUser(data) {
  return data;
}
Attempts:
2 left
💡 Hint

Remember the decorator syntax requires parentheses and a string argument.

🔧 Debug
advanced
2:00remaining
Why does this NestJS microservice handler not respond to messages?

Given this code, why does the microservice never respond to messages with pattern 'ping'?

NestJS
import { Controller } from '@nestjs/common';
import { MessagePattern } from '@nestjs/microservices';

@Controller()
export class PingController {
  @MessagePattern('ping')
  ping() {
    console.log('Ping received');
  }
}
AThe pattern string 'ping' is invalid and does not match any messages.
BThe handler does not return any value, so the client waits indefinitely.
CThe @Controller decorator is missing required parameters.
DThe method name 'ping' conflicts with reserved keywords.
Attempts:
2 left
💡 Hint

Think about what happens if a handler does not return a response.

❓ state_output
advanced
2:00remaining
What is the value of 'count' after these messages are processed?

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'?

NestJS
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;
  }
}
A3
B0
C1
DUndefined
Attempts:
2 left
💡 Hint

Each message triggers the increment method once.

🧠 Conceptual
expert
2:00remaining
Which statement about NestJS message patterns and request-response is true?

Choose the correct statement about how NestJS handles request-response message patterns in microservices.

AMessage patterns only support fire-and-forget messages and cannot return responses.
BNestJS automatically sends a default response if the handler method returns void or undefined.
CThe handler method must always return a value or a Promise to send a response back to the client.
DThe client must manually listen for responses; the handler does not send them automatically.
Attempts:
2 left
💡 Hint

Think about how request-response communication works in microservices.

Practice

(1/5)
1. What is the main purpose of the @MessagePattern decorator in NestJS?
easy
A. To define HTTP routes in a controller
B. To listen for specific message types and handle incoming messages
C. To send messages to other microservices
D. To configure database connections

Solution

  1. Step 1: Understand the role of @MessagePattern

    This decorator is used to mark a method that listens for messages matching a specific pattern.
  2. Step 2: Differentiate from other decorators

    Unlike HTTP route decorators, @MessagePattern is for message-based communication, not HTTP or database setup.
  3. Final Answer:

    To listen for specific message types and handle incoming messages -> Option B
  4. Quick Check:

    @MessagePattern listens for messages [OK]
Hint: Remember: @MessagePattern listens, not sends [OK]
Common Mistakes:
  • Confusing @MessagePattern with HTTP route decorators
  • Thinking it sends messages instead of listening
  • Assuming it configures databases
2. Which of the following is the correct way to define a message handler for the pattern 'sum_numbers' in NestJS?
easy
A. @Subscribe('sum_numbers') handleSum(data: number[]) { return data.reduce((a, b) => a + b); }
B. @Get('sum_numbers') handleSum(data: number[]) { return data.reduce((a, b) => a + b); }
C. @Post('sum_numbers') handleSum(data: number[]) { return data.reduce((a, b) => a + b); }
D. @MessagePattern('sum_numbers') handleSum(data: number[]) { return data.reduce((a, b) => a + b); }

Solution

  1. Step 1: Identify the correct decorator for message patterns

    @MessagePattern is the correct decorator to listen for messages, not @Get, @Post, or @Subscribe.
  2. 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.
  3. Final Answer:

    @MessagePattern('sum_numbers') handleSum(data: number[]) { return data.reduce((a, b) => a + b); } -> Option D
  4. Quick Check:

    Use @MessagePattern('pattern') for message handlers [OK]
Hint: Use @MessagePattern for message handlers, not HTTP decorators [OK]
Common Mistakes:
  • Using HTTP decorators like @Get or @Post for message patterns
  • Using non-existent decorators like @Subscribe
  • Forgetting to pass the pattern string to @MessagePattern
3. Given the following NestJS message handler, what will be the response when the message pattern 'multiply' is sent with data [2, 3]?
@MessagePattern('multiply')
handleMultiply(data: number[]) {
  return data[0] * data[1];
}
medium
A. 6
B. undefined
C. [2, 3]
D. 5

Solution

  1. 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].
  2. Step 2: Calculate the product for input [2, 3]

    2 * 3 equals 6, so the response will be 6.
  3. Final Answer:

    6 -> Option A
  4. Quick Check:

    2 multiplied by 3 equals 6 [OK]
Hint: Multiply first two array elements for 'multiply' pattern [OK]
Common Mistakes:
  • Adding instead of multiplying the numbers
  • Returning the input array instead of the product
  • Assuming undefined because of missing return
4. Identify the error in the following NestJS message handler code:
@MessagePattern('greet')
async handleGreet(name: string) {
  console.log('Greeting:', name);
}
medium
A. The @MessagePattern decorator is missing the pattern string
B. The method should not be async
C. The handler does not return a response to the sender
D. The parameter type should be an object, not a string

Solution

  1. 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.
  2. Step 2: Verify decorator and parameter correctness

    The decorator has the pattern string 'greet', and the parameter type string is acceptable for simple messages.
  3. Final Answer:

    The handler does not return a response to the sender -> Option C
  4. Quick Check:

    Handlers must return a response [OK]
Hint: Always return a value in message handlers [OK]
Common Mistakes:
  • Not returning a response causes sender to wait indefinitely
  • Confusing async usage with missing return
  • Assuming parameter type must be object always
5. You want to create a NestJS microservice that listens for a message pattern 'calculate' and returns the sum of two numbers sent in an object like { a: 5, b: 7 }. Which of the following handler implementations correctly achieves this?
hard
A. @MessagePattern('calculate') handleCalculate(data: { a: number; b: number }) { return data.a + data.b; }
B. @MessagePattern('calculate') handleCalculate(a: number, b: number) { return a + b; }
C. @MessagePattern('calculate') handleCalculate(data: number[]) { return data[0] + data[1]; }
D. @MessagePattern('calculate') handleCalculate(data: string) { return parseInt(data); }

Solution

  1. Step 1: Match the expected input structure

    The message sends an object with properties a and b, so the handler must accept an object with those properties.
  2. Step 2: Verify the handler logic

    The handler correctly accesses data.a and data.b and returns their sum.
  3. 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.
  4. Final Answer:

    @MessagePattern('calculate') handleCalculate(data: { a: number; b: number }) { return data.a + data.b; } -> Option A
  5. Quick Check:

    Match input shape and sum properties [OK]
Hint: Match handler parameter to message data shape exactly [OK]
Common Mistakes:
  • Using multiple parameters instead of one object
  • Expecting array when object is sent
  • Parsing string instead of object
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard