Complete the code to create a message pattern handler for 'get_data'.
import { Controller } from '@nestjs/common'; import { MessagePattern } from '@nestjs/microservices'; @Controller() export class DataController { @MessagePattern('[1]') getData() { return { data: 'Hello' }; } }
The @MessagePattern decorator listens for the exact message pattern string. Here, 'get_data' is the correct pattern to handle.
Complete the code to inject the ClientProxy and send a request with 'get_data' pattern.
import { Controller, Inject } from '@nestjs/common'; import { ClientProxy } from '@nestjs/microservices'; @Controller() export class AppController { constructor(@Inject('[1]') private client: ClientProxy) {} async requestData() { return this.client.send('get_data', {}).toPromise(); } }
The injection token must match the provider name registered in the module. 'DATA_SERVICE' is the correct token here.
Fix the error in the message handler to correctly receive data and return a response.
import { Controller } from '@nestjs/common'; import { MessagePattern } from '@nestjs/microservices'; @Controller() export class CalcController { @MessagePattern('sum') calculate([1]: number[]) { return data.reduce((a, b) => a + b, 0); } }
The parameter name must match the variable used inside the method. Here, 'data' is used in the reduce function, so it must be the parameter name.
Fill both blanks to create a message pattern handler that returns the square of a number.
import { Controller } from '@nestjs/common'; import { MessagePattern } from '@nestjs/microservices'; @Controller() export class MathController { @MessagePattern([1]) square([2]: number) { return num * num; } }
The message pattern string should be 'square_number' to match the event. The parameter name 'num' matches the variable used inside the method.
Fill all three blanks to send a request and handle the response with async/await.
import { Controller, Inject } from '@nestjs/common'; import { ClientProxy } from '@nestjs/microservices'; @Controller() export class AppController { constructor(@Inject([1]) private client: ClientProxy) {} async getResult() { const response = await this.client.send([2], [3]).toPromise(); return response; } }
The injection token is 'DATA_SERVICE' to match the provider. The message pattern is 'get_data' to request data. The payload is an empty object {} as no data is sent.