MessageHandler.ts 993 Bytes
import { Connection } from "../connection/Connection";
import { ServerInboundMessageMap, ServerResponse } from "../../common/index";

type ServerHandlerMap<T> = {
  [Key in keyof ServerInboundMessageMap]?: (
    connection: Connection,
    message: Omit<ServerInboundMessageMap[Key], "result">,
    scope: T
  ) => ServerResponse<
    "result" extends keyof ServerInboundMessageMap[Key]
      ? ServerInboundMessageMap[Key]["result"]
      : undefined
  >;
};

export class HandlerMap<T> {
  private scope: T;
  private handlers: ServerHandlerMap<T>;

  constructor(scope: T, handlers: ServerHandlerMap<T>) {
    this.scope = scope;
    this.handlers = handlers;
  }

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