Passed
Pull Request — main (#345)
by Alejandro
03:34
created

src/mercure/helpers/boundToMercureHub.tsx   A

Complexity

Total Complexity 4
Complexity/F 4

Size

Lines of Code 42
Function Count 1

Duplication

Duplicated Lines 0
Ratio 0 %

Test Coverage

Coverage 57.14%

Importance

Changes 0
Metric Value
wmc 4
eloc 36
mnd 3
bc 3
fnc 1
dl 0
loc 42
ccs 8
cts 14
cp 0.5714
rs 10
bpm 3
cpm 4
noi 0
c 0
b 0
f 0

1 Function

Rating   Name   Duplication   Size   Complexity  
A boundToMercureHub.tsx ➔ boundToMercureHub 0 28 4
1
import { FC, useEffect } from 'react';
2
import { pipe } from 'ramda';
3
import { CreateVisit } from '../../visits/types';
4
import { MercureInfo } from '../reducers/mercureInfo';
5
import { bindToMercureTopic } from './index';
6
7
export interface MercureBoundProps {
8
  createNewVisits: (createdVisits: CreateVisit[]) => void;
9
  loadMercureInfo: Function;
10
  mercureInfo: MercureInfo;
11
}
12
13
export function boundToMercureHub<T = {}>(
14
  WrappedComponent: FC<MercureBoundProps & T>,
15
  getTopicForProps: (props: T) => string,
16
) {
17 9
  const pendingUpdates = new Set<CreateVisit>();
18
19 9
  return (props: MercureBoundProps & T) => {
20 13
    const { createNewVisits, loadMercureInfo, mercureInfo } = props;
21 13
    const { interval } = mercureInfo;
22
23 13
    useEffect(() => {
24 2
      const onMessage = (visit: CreateVisit) => interval ? pendingUpdates.add(visit) : createNewVisits([ visit ]);
25
      const closeEventSource = bindToMercureTopic(mercureInfo, getTopicForProps(props), onMessage, loadMercureInfo);
26
27 2
      if (!interval) {
28
        return closeEventSource;
29
      }
30
31
      const timer = setInterval(() => {
32
        createNewVisits([ ...pendingUpdates ]);
33
        pendingUpdates.clear();
34
      }, interval * 1000 * 60);
35
36
      return pipe(() => clearInterval(timer), () => closeEventSource?.());
37
    }, [ mercureInfo ]);
38
39 13
    return <WrappedComponent {...props} />;
40
  };
41
}
42