MessageHandlerRegistry.ts 877 Bytes
import { Connection } from "../connection/Connection";
import { loginHandler } from "./handler/loginHandler";
import { roomJoinHandler } from "./handler/roomJoinHandler";
import { roomLeaveHandler } from "./handler/roomLeaveHandler";
import { Message, MessageType } from "./types";

export class MessageHandlerRegistry {
  static registerHandlers(connection: Connection) {
    this.registerHandler(connection, MessageType.LOGIN, loginHandler);
    this.registerHandler(connection, MessageType.ROOM_JOIN, roomJoinHandler);
    this.registerHandler(connection, MessageType.ROOM_LEAVE, roomLeaveHandler);
  }

  private static registerHandler<T extends Message>(
    connection: Connection,
    typeName: string,
    handler: (connection: Connection, message: T) => void
  ) {
    connection.socket.on(typeName, (message: T) => {
      handler(connection, message);
    });
  }
}