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

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

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