parser.ts 1.3 KB

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