Performance: WebSocket gateway creation
This affects the real-time communication speed and responsiveness between client and server.
import { WebSocketGateway, SubscribeMessage, MessageBody } from '@nestjs/websockets'; @WebSocketGateway() export class ChatGateway { @SubscribeMessage('message') async handleMessage(client: any, payload: any): Promise<void> { // offload heavy work asynchronously await someAsyncProcessing(payload); client.emit('message', payload); } } async function someAsyncProcessing(data: any) { return new Promise(resolve => setTimeout(resolve, 0)); }
import { WebSocketGateway, SubscribeMessage, MessageBody } from '@nestjs/websockets'; @WebSocketGateway() export class ChatGateway { @SubscribeMessage('message') handleMessage(client: any, payload: any): void { // heavy synchronous processing for (let i = 0; i < 1000000000; i++) {} client.emit('message', payload); } }
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Synchronous heavy processing in gateway | 0 | 0 | 0 | [X] Bad |
| Asynchronous non-blocking message handling | 0 | 0 | 0 | [OK] Good |
@WebSocketGateway().@WebSocketServer() is used inside the class to inject the server instance, not to define the class itself. The others are incorrect or do not exist.import { WebSocketGateway, SubscribeMessage, MessageBody } from '@nestjs/websockets';
@WebSocketGateway()
export class ChatGateway {
@SubscribeMessage('message')
handleMessage(@MessageBody() data: string): string {
console.log('Received:', data);
return `Echo: ${data}`;
}
}import { WebSocketGateway, SubscribeMessage } from '@nestjs/websockets';
@WebSocketGateway()
export class MyGateway {
@SubscribeMessage('chat')
onChat(data: string) {
return `Message: ${data}`;
}
}@MessageBody().@WebSocketGateway() can be used without a port, and the method does not need to be async unless awaiting something.@WebSocketServer() and call emit on it.client.send() targets one client. The decorator @SubscribeMessage() only listens for events, it does not broadcast.Pass the test and this pattern moves unknown