src/mercure/helpers/index.js   A
last analyzed

Complexity

Total Complexity 1
Complexity/F 0

Size

Lines of Code 29
Function Count 0

Duplication

Duplicated Lines 0
Ratio 0 %

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
wmc 1
eloc 23
mnd 1
bc 1
fnc 0
dl 0
loc 29
ccs 12
cts 12
cp 1
rs 10
bpm 0
cpm 0
noi 0
c 0
b 0
f 0
1
import { useEffect } from 'react';
2
import { EventSourcePolyfill as EventSource } from 'event-source-polyfill';
3
4 29
export const bindToMercureTopic = (mercureInfo, topic, onMessage, onTokenExpired) => () => {
5 4
  const { mercureHubUrl, token, loading, error } = mercureInfo;
6
7 4
  if (loading || error) {
8 3
    return undefined;
9
  }
10
11 1
  const hubUrl = new URL(mercureHubUrl);
12
13 1
  hubUrl.searchParams.append('topic', topic);
14 1
  const es = new EventSource(hubUrl, {
15
    headers: {
16
      Authorization: `Bearer ${token}`,
17
    },
18
  });
19
20 1
  es.onmessage = ({ data }) => onMessage(JSON.parse(data));
21 2
  es.onerror = ({ status }) => status === 401 && onTokenExpired();
22
23 1
  return () => es.close();
24
};
25
26 5
export const useMercureTopicBinding = (mercureInfo, topic, onMessage, onTokenExpired) => {
27 25
  useEffect(bindToMercureTopic(mercureInfo, topic, onMessage, onTokenExpired), [ mercureInfo ]);
28
};
29