Consider this NestJS WebSocket gateway code. What will be logged when a client connects?
import { WebSocketGateway, OnGatewayConnection } from '@nestjs/websockets'; @WebSocketGateway() export class MyGateway implements OnGatewayConnection { handleConnection(client: any, ...args: any[]) { console.log('Client connected:', client.id); } }
Check how the handleConnection method works in a gateway implementing OnGatewayConnection.
The handleConnection method is called automatically when a client connects. The client object has an id property, so it logs the message with the id.
Choose the correct way to define a WebSocket gateway with the namespace '/chat'.
Remember the Gateway decorator accepts an options object for namespace.
The @WebSocketGateway decorator accepts an options object where namespace is specified as a property. Passing a string directly sets the port, not the namespace.
Given this gateway class implementing OnGatewayDisconnect but missing the @WebSocketGateway() decorator, what is the behavior when a client disconnects?
import { OnGatewayDisconnect } from '@nestjs/websockets'; export class MyGateway implements OnGatewayDisconnect { handleDisconnect(client: any) { console.log('Client disconnected:', client.id); } }
Think about what the decorator does in NestJS gateways.
Without the @WebSocketGateway() decorator, NestJS does not recognize the class as a gateway, so lifecycle hooks like handleDisconnect are not called.
Examine the code below. Why does the sendMessage method not send messages to connected clients?
import { WebSocketGateway, WebSocketServer } from '@nestjs/websockets'; import { Server } from 'socket.io'; @WebSocketGateway() export class ChatGateway { @WebSocketServer() server: Server; sendMessage(message: string) { this.server.emit('message', message); } }
Check if the method that emits messages is actually used.
The sendMessage method is defined but never called, so no messages are sent. The server property and decorator usage are correct.
Consider this gateway decorator:
@WebSocketGateway({ transports: ['websocket'] })What does setting transports to ['websocket'] do?
Think about how Socket.IO handles transports.
Setting transports to ['websocket'] disables HTTP long-polling fallback and forces clients to connect only via WebSocket.