Performance: WebSocket guards and pipes
MEDIUM IMPACT
This concept affects the responsiveness and throughput of WebSocket message handling by controlling access and transforming data before processing.
import { SubscribeMessage, WebSocketGateway } from '@nestjs/websockets'; import { UseGuards, UsePipes, ValidationPipe } from '@nestjs/common'; import { WsGuard } from './ws.guard'; @WebSocketGateway() export class ChatGateway { @UseGuards(WsGuard) @UsePipes(new ValidationPipe({ transform: true })) @SubscribeMessage('message') handleMessage(client, payload) { // Payload is already validated and transformed return { text: payload.text }; } }
import { SubscribeMessage, WebSocketGateway } from '@nestjs/websockets'; @WebSocketGateway() export class ChatGateway { @SubscribeMessage('message') handleMessage(client, payload) { // Manual validation and transformation inside handler if (!payload.text || typeof payload.text !== 'string') { return { error: 'Invalid message' }; } const transformed = payload.text.trim().toLowerCase(); // Process message return { text: transformed }; } }
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Manual validation in handler | N/A | N/A | N/A | [X] Bad |
| Validation and transformation via guards and pipes | N/A | N/A | N/A | [OK] Good |