ChatGateway@WebSocketGateway decorator on the ChatGateway classhandleMessage that will receive messages@SubscribeMessage decorator on the handleMessage methodChatGateway@WebSocketGateway decorator on the ChatGateway classhandleMessage that will receive messages@SubscribeMessage decorator on the handleMessage methodChatGateway and decorate it with @WebSocketGateway() from @nestjs/websockets.Remember to import WebSocketGateway from @nestjs/websockets and use it as a decorator above the class.
SubscribeMessage from @nestjs/websockets and add a method named handleMessage inside ChatGateway.Use @SubscribeMessage('message') above the handleMessage method to listen for 'message' events.
handleMessage method, return the payload parameter.Simply return the payload to send it back to the client.
export default ChatGateway; at the end of the file to export the class as default.Use export default ChatGateway; to make the class available for import elsewhere.
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