MessageHandler.ts 795 Bytes
import { Connection } from "../connection/Connection";
import {
  ServerInboundMessage,
  ServerInboundMessageMap,
  ServerResponse,
} from "../../common/index";
import { User } from "../user/User";

type UserHandlerMap = {
  [Key in keyof ServerInboundMessageMap]?: (
    user: User,
    message: ServerInboundMessage<Key>
  ) => ServerResponse<Key>;
};

export class MessageHandler {
  private handlers: UserHandlerMap;

  constructor(handlers: UserHandlerMap) {
    this.handlers = handlers;
  }

  public handle(
    type: keyof ServerInboundMessageMap,
    user: User,
    message: any,
    callback: Function
  ): boolean {
    const handler = this.handlers[type];
    if (!handler) return false;
    const response = handler(user, message);
    callback(response);
    return true;
  }
}