User.ts 1.62 KB
import { UserData } from "../../common/dataType";
import { Connection } from "../connection/Connection";
import { MessageHandler } from "../message/MessageHandler";
import { Room } from "../room/Room";
import { RoomManager } from "../room/RoomManager";
import { v4 as uuidv4 } from "uuid";

export class User {
  public readonly username: string; // TODO: 실제 역할은 uuid임
  public readonly nickname: string;

  public readonly connection: Connection;

  public room?: Room;

  public handler: MessageHandler;

  constructor(nickname: string, connection: Connection) {
    this.username = uuidv4();
    this.nickname = nickname;
    this.connection = connection;
    this.handler = new MessageHandler({
      roomList: (user, message) => {
        return { ok: true, result: connection.roomManager.list() };
      },
      createRoom: (user, message) => {
        if (user.room) {
          return { ok: false };
        }
        if (message.name.length >= 30 || message.name.trim().length === 0) {
          return { ok: false };
        }
        const room = connection.roomManager.create(message.name, 8, user);
        return { ok: true, result: room.getInfo() };
      },
      joinRoom: (user, message) => {
        const room = connection.roomManager.get(message.uuid);
        if (user.room || !room) {
          return { ok: false };
        }
        // TODO: 방 접속 실패 처리
        room.connect(user);
        if (user.room === undefined) {
          return { ok: false };
        }
        return { ok: true, result: room.getInfo() };
      },
    });
  }

  public disconnected(): void {
    this.room?.disconnect(this);
  }
}