Performance: Gateway decorator
This affects the initialization and event handling speed of WebSocket gateways in a NestJS application, impacting interaction responsiveness.
import { WebSocketGateway, SubscribeMessage } from '@nestjs/websockets'; @WebSocketGateway() export class ChatGateway { @SubscribeMessage('message') async handleMessage(client: any, payload: any) { // offload heavy work asynchronously await new Promise(resolve => setTimeout(resolve, 0)); return { event: 'message', data: payload }; } }
import { WebSocketGateway, SubscribeMessage } from '@nestjs/websockets'; @WebSocketGateway() export class ChatGateway { @SubscribeMessage('message') handleMessage(client: any, payload: any) { // heavy synchronous processing for(let i = 0; i < 1000000000; i++) {} return { event: 'message', data: payload }; } }
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Heavy synchronous event handler | N/A | N/A | N/A | [X] Bad |
| Asynchronous lightweight event handler | N/A | N/A | N/A | [OK] Good |
What is the main purpose of the @WebSocketGateway() decorator in NestJS?
Which of the following is the correct syntax to create a WebSocket gateway with a custom namespace /chat?
?@WebSocketGateway() decorator accepts an options object where namespace is a valid key to set the namespace.{ namespace: '/chat' }. @WebSocketGateway('/chat')
export class ChatGateway {} incorrectly passes a string directly. @WebSocketGateway(namespace: '/chat')
export class ChatGateway {} uses invalid syntax. @WebSocketGateway({ path: '/chat' })
export class ChatGateway {} uses path which is not the correct key for namespace.Given the following code, what will be the output when a client connects?
@WebSocketGateway()
export class MyGateway {
handleConnection(client: any) {
console.log('Client connected');
}
}handleConnection is a lifecycle method called automatically when a client connects.Identify the error in this WebSocket gateway code:
@WebSocketGateway()
export class AppGateway {
@SubscribeMessage('message')
handleMessage(client, payload) {
client.emit('message', payload);
}
}client.emit is incorrect; the framework handles sending the return value automatically.You want to create a WebSocket gateway that listens on port 8081 and uses the namespace /notifications. Which of the following is the correct way to define this gateway?
@WebSocketGateway() decorator accepts a single options object where you can specify both port and namespace.port and namespace. @WebSocketGateway(8081, { namespace: '/notifications' })
export class NotificationGateway {} incorrectly uses positional arguments mixing number and object. @WebSocketGateway({ port: 8081 })
@WebSocketGateway({ namespace: '/notifications' })
export class NotificationGateway {} uses two decorators which is invalid. @WebSocketGateway('/notifications', 8081)
export class NotificationGateway {} uses positional arguments in wrong order and types.Pass the test and this pattern moves unknown