MessageHandlerChain.ts 1.41 KB
import { Connection } from "../connection/Connection";
import {
  ServerInboundMessage,
  ServerInboundMessageMap,
  ServerResponse,
} from "../../common/index";
import { keys } from "ts-transformer-keys";
import { User } from "../user/User";

export class MessageHandlerChain {
  connection: Connection;

  constructor(connection: Connection) {
    this.connection = connection;

    // 유저 정보가 없으므로 로그인은 따로 핸들링
    this.connection.socket.on(
      "login",
      (message: ServerInboundMessage<"login">, callback: Function) => {
        connection.user = new User(message.username, connection);
        console.log(`User ${message.username} has logged in!`);

        callback({ ok: true });
      }
    );

    for (const key in keys<ServerInboundMessageMap>()) {
      const type = key as keyof ServerInboundMessageMap;
      this.connection.socket.on(key, (message: any, callback: Function) => {
        // Game > Room > User 순으로 전달
        if (
          connection?.user?.room &&
          connection.user.room.handler.handle(
            type,
            connection.user,
            message,
            callback
          )
        )
          return;

        if (
          connection?.user &&
          connection.user.handler.handle(
            type,
            connection.user,
            message,
            callback
          )
        )
          return;
      });
    }
  }
}