MessageHandlerChain.ts 1.46 KB
import { Connection } from "../connection/Connection";
import {
  RawMessage,
  ServerInboundMessage,
  ServerInboundMessageKey,
  ServerResponse,
} from "../../common/index";
import { User } from "../user/User";

export class MessageHandlerChain {
  connection: Connection;

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

    this.connection.socket.on("msg", (raw: RawMessage, callback: Function) => {
      this.handleRaw(connection, raw, callback);
    });
  }

  private handleRaw(
    connection: Connection,
    raw: RawMessage,
    callback: Function
  ) {
    const type = raw.type as ServerInboundMessageKey;
    const message = raw.message;

    // 유저 정보가 없으므로 로그인은 따로 핸들링
    if (type === "login") {
      this.handleLogin(connection, message, callback);
      return;
    }

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

  private handleLogin(
    connection: Connection,
    message: ServerInboundMessage<"login">,
    callback: Function
  ) {
    connection.user = new User(message.username, connection);
    console.log(`User ${message.username} has logged in!`);

    callback({ ok: true });
  }
}