Chat server using WebSockets with Nest framework.
npm install
# development
npm run start
# watch mode
npm run start:dev
npm i --save @nestjs/websockets @nestjs/platform-socket.io ngx-socket-io
npm i --save-dev @types/socket.io
-
We add
@WebSocketServer() server;
inside of our ChatWebsocketGateway to attaches a native Web Socket Server to our propertyserver
and then we use the decorator@WebSocketGateway(port?: number)
to mark our WebsocketGateway class as a Nest gateway that enables real-time, bidirectional and event-based communication between the browser and the server -
In order de hand the connection and disconnection at our websocket server we need to implement interfaces
OnGatewayConnection
andOnGatewayDisconnect
. -
We use decorator
@SubscribeMessage('exmple-channel')
on the method that handles our business rules onexmple-channel
events, for example we use@SubscribeMessage('chat')
to cap and handle the chat events. You can implement a custom subscriber as:@SubscribeMessage({channel: 'messages', type: 'group'})
in order to hand messages event of groups only.
-
/api/v1/rooms
roomId: the room id (room name) creatorUsername: the username with creats the room
curl -X POST 'http://localhost:3000/api/v1/rooms' \ --data-raw '{ "roomId": "3XX", "creatorUsername": "idirnaitali" }'
- Invalid body:
{ "statusCode": 400, "message": [ "roomId should not be empty", "creatorUsername should not be empty" ], "error": "Bad Request" }
- Existing room id:
{ "code": "room.conflict", "message": "Room with 'exmple-room' already exists" }
-
/api/v1/rooms/{roomId}/messages?fromIndex={fromIndex}&toIndex={fromIndex}
roomId: the room id fromIndex: the index of the first message to get fromIndex: the index of the last message to get
curl -X GET 'http://localhost:3000/api/v1/rooms/3XX/messages?fromIndex=1&toIndex=20'
- Invalid room id (ex: not found or closed):
{ "code": "access-forbidden", "message": "The access is forbidden" }
- Missing
fromIndex
/toIndex
:
{ "statusCode": 400, "message": "Validation failed (numeric string is expected)", "error": "Bad Request" }
- Invalid
fromIndex
/toIndex
:
{ "code": "req-params.validation", "message": "Invalid parameters, 'fromIndex' and 'toIndex' must be positive" }
- Invalid
fromIndex
/toIndex
:
{ "code": "req-params.validation", "message": "Invalid parameters, 'toIndex' must no not be less than 'fromIndex'" }
-
/api/v1/rooms/{roomId}
roomId: the room id
curl -X DELETE http://localhost:3000/api/v1/rooms/3XX
- Invalid room id (ex: not found or closed):
{ "code": "room.not-fond", "message": "Room with '3XX' not found" }