All files / packages/tools/src/store/SynchronizerManager createSynchronizer.ts

100% Statements 7/7
100% Branches 2/2
100% Functions 2/2
100% Lines 7/7

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                                    3x 1x     3x 1x       2x             2x     2x        
import { state } from '../index';
import Synchronizer from './Synchronizer';
import { ISynchronizerEventHandler } from '../../types';
 
/**
 * Create a new synchronizer instance from Synchronizer class
 * @param synchronizerId - The id of the synchronizer.
 * @param eventName - The name of the event that will be emitted by the
 * synchronizer.
 * @param eventHandler - The event handler that will be
 * called when the event is emitted.
 * @returns A reference to the synchronizer.
 */
function createSynchronizer(
  synchronizerId: string,
  eventName: string,
  eventHandler: ISynchronizerEventHandler
): Synchronizer {
  const synchronizerWithSameIdExists = state.synchronizers.some(
    (sync) => sync.id === synchronizerId
  );
 
  if (synchronizerWithSameIdExists) {
    throw new Error(`Synchronizer with id '${synchronizerId}' already exists.`);
  }
 
  // Create
  const synchronizer = new Synchronizer(
    synchronizerId,
    eventName,
    eventHandler
  );
 
  // Update state
  state.synchronizers.push(synchronizer);
 
  // Return reference
  return synchronizer;
}
 
export default createSynchronizer;