-
-
Save gdyrrahitis/ab77caa0ab6f3348890b0a275ae7742a to your computer and use it in GitHub Desktop.
Socket class
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import * as uuidV1 from "uuid/v1"; | |
import { Constants } from "./constants"; | |
import { getFirst, filter, isUndefined, Guard } from "../../shared/index"; | |
import { Room, User, UserRole, Roles } from "../../domain/index"; | |
import { | |
InternalServerErrorEvent, RoomsFullEvent, RoomShowAllEvent, RoomDisconnectEvent, | |
RoomNotFoundEvent, UserBannedEvent, UserDisconnectedEvent, RoomCreateEvent, | |
BanEvent, RequestAllRoomsEvent, RequestAllUsersEvent, RoomGetAllEvent, | |
RoomJoinEvent, RoomsAllEvent, UsersAllEvent, ConnectionEvent | |
} from "../../domain/events/index"; | |
const max: number = (<ServerAppConfig.ServerConfiguration>require("../server.config.json")).socketio.maxRoomsAllowed; | |
export class Socket { | |
private rooms: Room[] = []; | |
constructor(private io: SocketIO.Server) { } | |
public connect() { | |
this.io.on(ConnectionEvent.eventName, (socket: ISocket) => { | |
socket.on(RoomCreateEvent.eventName, (data: CreateRoomEventArgs, callback: CreateRoomEventCallback) => { | |
try { | |
createRoom(data, callback); | |
} catch (error) { | |
callback({ access: false }); | |
this.emitInternalServerError(socket, error); | |
} | |
}); | |
let createRoom = (data: CreateRoomEventArgs, callback: CreateRoomEventCallback) => { | |
Guard.throwIfObjectUndefined(data, Constants.dataIsRequired); | |
Guard.throwIfStringNotDefinedOrEmpty(data.name, Constants.dataNameIsRequired); | |
let isCurrentUserInAnyOtherRoom = this.rooms.filter(r => !!r.getUser(socket.id)).length > 0; | |
Guard.validate(isCurrentUserInAnyOtherRoom, Constants.youAreAlreadyInAnotherRoom); | |
if (this.hasRoomsReachedMaxLimit()) { | |
callback({ access: false }); | |
socket.emit(RoomsFullEvent.eventName); | |
return; | |
} | |
let room = this.createRoom(); | |
this.rooms.push(room); | |
this.createUser(socket.id, data.name) | |
.addToRoom(room) | |
.makeSocketJoinRoom(socket, room.id); | |
this.emitLoggedUsersToRoom(socket, room); | |
callback({ access: true, roomId: room.id }); | |
this.emitRoomsAllEventWithTotalRooms(); | |
this.emitUsersAllEventWithTotalUsersInAllRooms(); | |
} | |
// More handlers in same manner. just look at the repository if you want more... | |
} | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment