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

src/mercure/helpers/index.ts   A

Complexity

Total Complexity 1
Complexity/F 0

Size

Lines of Code 25
Function Count 0

Duplication

Duplicated Lines 0
Ratio 0 %

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
wmc 1
eloc 20
mnd 1
bc 1
fnc 0
dl 0
loc 25
ccs 10
cts 10
cp 1
rs 10
bpm 0
cpm 0
noi 0
c 0
b 0
f 0
1
import { EventSourcePolyfill as EventSource } from 'event-source-polyfill';
2
import { MercureInfo } from '../reducers/mercureInfo';
3
4 6
export const bindToMercureTopic = <T>(mercureInfo: MercureInfo, topic: string, onMessage: (message: T) => void, onTokenExpired: Function) => { // eslint-disable-line max-len
5 6
  const { mercureHubUrl, token, loading, error } = mercureInfo;
6
7 6
  if (loading || error || !mercureHubUrl) {
8 5
    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 }: { data: string }) => onMessage(JSON.parse(data) as T);
21 2
  es.onerror = ({ status }: { status: number }) => status === 401 && onTokenExpired();
22
23 1
  return () => es.close();
24
};
25