MessageHandlerRegistry.ts 1.43 KB
import { Connection } from "../connection/Connection";
import { User } from "../user/User";
import { loginHandler } from "./handler/loginHandler";
import { roomChatHandler } from "./handler/roomChatHandler";
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.registerHandlerAuthed(
      connection,
      MessageType.ROOM_JOIN,
      roomJoinHandler
    );
    this.registerHandlerAuthed(
      connection,
      MessageType.ROOM_LEAVE,
      roomLeaveHandler
    );
    this.registerHandlerAuthed(
      connection,
      MessageType.ROOM_CHAT,
      roomChatHandler
    );
  }

  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);
    });
  }

  private static registerHandlerAuthed<T extends Message>(
    connection: Connection,
    typeName: string,
    handler: (user: User, message: T) => void
  ) {
    connection.socket.on(typeName, (message: T) => {
      if (connection.user !== undefined) {
        handler(connection.user, message);
      }
    });
  }
}