All files / src/components/common/Error ErrorEmitter.tsx

38.09% Statements 8/21
25% Branches 1/4
20% Functions 2/10
42.1% Lines 8/19

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56                      309x 309x     309x       309x 309x 309x   309x                                                             309x  
// useErrorEmitter.ts
import { useEffect, useState } from "react";
 
export type ErrorListener<T> = (payload: T) => void;
 
interface Subscription {
  eventName: string;
  listener: ErrorListener<any>;
}
 
export class GiveErrorEmitter {
  private subscriptions: Subscription[] = [];
  private static instance: GiveErrorEmitter | null = null;
 
  private constructor() {
    this.subscriptions = [];
  }
 
  static getInstance(): GiveErrorEmitter {
    Eif (!GiveErrorEmitter.instance) {
      GiveErrorEmitter.instance = new GiveErrorEmitter();
      GiveErrorEmitter.instance.subscriptions = [];
    }
    return GiveErrorEmitter.instance;
  }
 
  subscribe(eventName: string, listener: ErrorListener<any>): () => void {
    const subscription: Subscription = { eventName, listener };
    this.subscriptions.push(subscription);
 
    return () => {
      this.subscriptions = this.subscriptions.filter((s) => s !== subscription);
    };
  }
 
  castError(eventName: string, payload: any): void {
    const relevantListeners = this.subscriptions.filter(
      (s) => s.eventName === eventName,
    );
    relevantListeners.forEach((subscription) => subscription.listener(payload));
    
  }
 
  clearListeners(eventName?: string): void {
    if (eventName) {
      this.subscriptions = this.subscriptions.filter(
        (s) => s.eventName !== eventName,
      );
    } else {
      this.subscriptions = [];
    }
  }
}
 
export const ErrorEmitter = GiveErrorEmitter.getInstance();