parser.ts 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. import { Ok, Err, Result } from "ts-results/result";
  2. import { FlowyError } from "../models/flowy-error";
  3. import { SubscribeObject } from "../models/flowy-notification";
  4. export declare type OnNotificationPayload<T> = (ty: T, payload: Uint8Array) => void;
  5. export declare type OnNotificationError = (error: FlowyError) => void;
  6. export declare type NotificationTyParser<T> = (num: number) => T | null;
  7. export declare type ErrParser<E> = (data: Uint8Array) => E;
  8. export abstract class NotificationParser<T> {
  9. id?: String;
  10. onPayload: OnNotificationPayload<T>;
  11. onError?: OnNotificationError;
  12. tyParser: NotificationTyParser<T>;
  13. constructor(onPayload: OnNotificationPayload<T>, tyParser: NotificationTyParser<T>, id?: String, onError?: OnNotificationError) {
  14. this.id = id;
  15. this.onPayload = onPayload;
  16. this.onError = onError;
  17. this.tyParser = tyParser;
  18. }
  19. parse(subject: SubscribeObject) {
  20. if (typeof this.id !== "undefined" && this.id.length == 0) {
  21. if (subject.id != this.id) {
  22. return;
  23. }
  24. }
  25. let ty = this.tyParser(subject.ty);
  26. if (ty == null) {
  27. return;
  28. }
  29. if (subject.has_error) {
  30. let error = FlowyError.deserializeBinary(subject.error);
  31. this.onError?.(error);
  32. } else {
  33. this.onPayload(ty, subject.payload);
  34. }
  35. }
  36. }