Spaces:
Sleeping
Sleeping
| import RoomServices from './RoomServices.js' | |
| import WebSocket from 'ws' | |
| class MessageService { | |
| username: string | |
| message: string | |
| room_id: string | |
| action: string | |
| rooms: RoomServices | |
| con: WebSocket | |
| constructor({ | |
| msg, | |
| rooms, | |
| con, | |
| }: { | |
| msg: string | |
| rooms: RoomServices | |
| con: WebSocket | |
| }) { | |
| const layers = JSON.parse(msg) | |
| this.room_id = layers['room_id'] | |
| this.username = layers['username'] | |
| this.message = layers['message'] | |
| this.action = layers['action'] | |
| this.rooms = rooms | |
| this.con = con | |
| if (this.action.toLowerCase() === 'join') { | |
| this.join() | |
| } else if (this.action.toLowerCase() === 'leave') { | |
| this.leave() | |
| } else { | |
| this.broadcast() | |
| } | |
| } | |
| join() { | |
| this.rooms.putRoom(this.room_id, this.username, this.con) | |
| this.broadcast() | |
| } | |
| leave() { | |
| this.rooms.leaveRoom(this.room_id, this.username) | |
| this.broadcast() | |
| } | |
| broadcast() { | |
| if (!this.rooms.hasRoom(this.room_id)) return | |
| if (!this.rooms.getRoom(this.room_id)) return | |
| let arr_rooms = this.rooms.getRoom(this.room_id) | |
| if (!arr_rooms) return | |
| for (const [key, value] of arr_rooms) { | |
| if (this.action.toLowerCase() === 'join') { | |
| value.send( | |
| `${this.username} has joined the ${this.room_id} chat!` | |
| ) | |
| } else if (this.action.toLowerCase() === 'leave') { | |
| value.send( | |
| `${this.username} has left the ${this.room_id} chat!` | |
| ) | |
| } else { | |
| value.send(`${this.username}: ${this.message}`) | |
| } | |
| } | |
| } | |
| broadcast_message(msg: string) { | |
| if (!this.rooms.hasRoom(this.room_id)) return | |
| if (!this.rooms.getRoom(this.room_id)) return | |
| let arr_rooms = this.rooms.getRoom(this.room_id) | |
| if (!arr_rooms) return | |
| for (const [key, value] of arr_rooms) { | |
| value.send(`${this.username}: ${msg}`) | |
| } | |
| } | |
| } | |
| export default MessageService | |