MessageHandlerRegistry.ts 1.73 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, MessageResponse, 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,
    S extends Message | undefined
  >(
    connection: Connection,
    typeName: string,
    handler: (connection: Connection, message: T) => MessageResponse<S>
  ) {
    connection.socket.on(typeName, (message: T, callback: Function) => {
      const response = handler(connection, message);
      callback(response);
    });
  }

  private static registerHandlerAuthed<
    T extends Message,
    S extends Message | undefined
  >(
    connection: Connection,
    typeName: string,
    handler: (user: User, message: T) => MessageResponse<S>
  ) {
    connection.socket.on(typeName, (message: T, callback: Function) => {
      if (connection.user !== undefined) {
        const response = handler(connection.user, message);
        callback(response);
      } else {
        callback({ ok: false });
      }
    });
  }
}