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