Complete the code to apply a guard to a WebSocket gateway method.
import { UseGuards } from '@nestjs/common'; import { WebSocketGateway, SubscribeMessage } from '@nestjs/websockets'; import { AuthGuard } from './auth.guard'; @WebSocketGateway() export class ChatGateway { @[1](AuthGuard) @SubscribeMessage('message') handleMessage(client: any, payload: any) { return payload; } }
The @UseGuards decorator is used to apply guards to WebSocket gateway methods in NestJS.
Complete the code to create a simple WebSocket pipe that transforms incoming data.
import { PipeTransform, Injectable } from '@nestjs/common'; @Injectable() export class [1] implements PipeTransform { transform(value: any) { return value.toUpperCase(); } }
The pipe class name should describe its function. Here, UppercasePipe fits because it transforms input to uppercase.
Fix the error in applying a guard to a WebSocket gateway method.
import { UseGuards } from '@nestjs/common'; import { WebSocketGateway, SubscribeMessage } from '@nestjs/websockets'; import { AuthGuard } from './auth.guard'; @WebSocketGateway() export class NotificationGateway { @UseGuards([1]) @SubscribeMessage('notify') handleNotify(client: any, payload: any) { return payload; } }
The @UseGuards decorator expects the guard class, not an instance or a call.
Fill both blanks to apply a pipe and a guard to a WebSocket gateway method.
import { UseGuards, UsePipes } from '@nestjs/common'; import { WebSocketGateway, SubscribeMessage } from '@nestjs/websockets'; import { AuthGuard } from './auth.guard'; import { ValidationPipe } from './validation.pipe'; @WebSocketGateway() export class MessageGateway { @[1](AuthGuard) @[2](ValidationPipe) @SubscribeMessage('send') handleSend(client: any, payload: any) { return payload; } }
Use @UseGuards to apply guards and @UsePipes to apply pipes on methods.
Fill all three blanks to create a WebSocket pipe that validates and transforms data, then apply it with a guard.
import { PipeTransform, Injectable, ArgumentMetadata } from '@nestjs/common'; import { UseGuards, UsePipes } from '@nestjs/common'; import { WebSocketGateway, SubscribeMessage } from '@nestjs/websockets'; import { AuthGuard } from './auth.guard'; @Injectable() export class [1] implements PipeTransform { transform(value: any, metadata: ArgumentMetadata) { if (typeof value !== 'string') { throw new Error('Invalid data'); } return value.trim(); } } @WebSocketGateway() export class DataGateway { @UseGuards([2]) @UsePipes([3]) @SubscribeMessage('data') handleData(client: any, payload: any) { return payload; } }
The pipe class is named TrimPipe and is applied with @UsePipes(TrimPipe). The guard is AuthGuard.