Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to create a WebSocket gateway using the correct decorator.
NestJS
import { [1] } from '@nestjs/websockets'; @[1]() export class ChatGateway {}
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using @Controller instead of @Gateway
Forgetting to import the decorator
Using @Injectable which is for services
✗ Incorrect
The @Gateway() decorator marks a class as a WebSocket gateway in NestJS.
2fill in blank
mediumComplete the code to specify the namespace for the gateway.
NestJS
import { Gateway, WebSocketServer } from '@nestjs/websockets'; @Gateway({ namespace: '[1]' }) export class ChatGateway { @WebSocketServer() server; }
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Omitting the leading slash in the namespace
Using an unrelated string as namespace
Not passing an object to @Gateway
✗ Incorrect
The namespace should start with a slash '/' to define the WebSocket namespace correctly.
3fill in blank
hardFix the error in the gateway decorator usage.
NestJS
import { Gateway } from '@nestjs/websockets'; @Gateway({ [1]: '/chat' }) export class ChatGateway {}
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'path' or 'url' instead of 'namespace'
Misspelling 'namespace'
Passing a string directly instead of an object
✗ Incorrect
The correct property to specify the WebSocket namespace is 'namespace'.
4fill in blank
hardFill both blanks to import and use the decorator that marks a method as a message handler.
NestJS
import { Gateway, [1] } from '@nestjs/websockets'; @Gateway() export class ChatGateway { @[2]('message') handleMessage(client, payload) { // handle incoming message } }
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using @MessageHandler which does not exist
Using @OnMessage or @HandleMessage which are incorrect
Forgetting to import the decorator
✗ Incorrect
The @SubscribeMessage decorator marks a method as a handler for a specific WebSocket message event.
5fill in blank
hardFill all three blanks to correctly inject the WebSocket server and emit an event.
NestJS
import { Gateway, WebSocketServer, SubscribeMessage } from '@nestjs/websockets'; import { Server } from 'socket.io'; @Gateway() export class ChatGateway { @[1]() server: [2]; @SubscribeMessage('sendMessage') handleSendMessage(client, payload) { this.server.[3]('newMessage', payload); } }
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'on' instead of 'emit' to send events
Not typing the server property as Server
Forgetting the @WebSocketServer decorator
✗ Incorrect
Use @WebSocketServer to inject the server instance of type Server, then call emit to send events.