MessageHandlerChain.ts 1.16 KB
import { Connection } from "../connection/Connection";
import { ServerInboundMessageMap, ServerResponse } from "../../common/index";
import { keys } from "ts-transformer-keys";
import { HandlerMap } from "./MessageHandler";
import { loginHandler } from "./handler/loginHandler";

export class MessageHandlerChain {
  connection: Connection;

  handler: HandlerMap<undefined>;

  constructor(connection: Connection) {
    this.connection = connection;
    this.handler = new HandlerMap(undefined, {
      login: loginHandler,
    });

    for (const key in keys<ServerInboundMessageMap>()) {
      const type = key as keyof ServerInboundMessageMap;
      this.connection.socket.on(key, (message: any, callback: Function) => {
        if (
          connection?.user?.room &&
          connection.user.room.handler.handle(
            type,
            connection,
            message,
            callback
          )
        )
          return;

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

        this.handler.handle(type, connection, message, callback);
      });
    }
  }
}