Total Complexity | 1 |
Complexity/F | 0 |
Lines of Code | 29 |
Function Count | 0 |
Duplicated Lines | 0 |
Ratio | 0 % |
Coverage | 100% |
Changes | 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 |