MessageValidator.ts 954 Bytes
import {
  ServerInboundMessageKey,
  ServerInboundMessageRecordMap,
} from "../../common";
import { Record } from "runtypes";

export class MessageValidator {
  private readonly messageRecordMap: Map<
    ServerInboundMessageKey,
    Record<any, boolean>
  > = new Map();
  constructor() {
    const messageRecordMapContainsResult = new ServerInboundMessageRecordMap();
    for (const key in messageRecordMapContainsResult) {
      const recordContainsResult =
        messageRecordMapContainsResult[
          key as keyof ServerInboundMessageRecordMap
        ];
      //@ts-ignore because some of entries don't have result property.
      this.messageRecordMap.set(key, recordContainsResult.omit("result"));
    }
  }

  public validate(key: ServerInboundMessageKey, message: any) {
    const messageRecord = this.messageRecordMap.get(key);
    if (messageRecord) {
      return messageRecord.validate(message).success;
    }
    return false;
  }
}