-
Notifications
You must be signed in to change notification settings - Fork 1
/
useStompNotificationsProvider.tsx
116 lines (104 loc) · 3.21 KB
/
useStompNotificationsProvider.tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
import {SnackbarProvider} from 'notistack';
import type {SnackbarProviderProps} from 'notistack';
import React, {useEffect, useMemo, useState} from 'react';
import UseStompCtx from './context';
import useToggle from './useToggle';
import WebSocketWorker from './webSocketWorker';
export type UseStompNotificationsProviderProps = SnackbarProviderProps & {
/**
* url to connect to stomp protocol
*/
url: string;
/**
* request auth header will be passed to the server or agent through the STOMP connection frame
*/
authHeader?: string;
/**
* request header will be passed to the server or agent through the STOMP connection frame
*/
headers?: Record<string, unknown>;
/**
* interval(ms) of attempts to reconnect when the websocket connection is dropped; default is 10,000ms
*/
reconnectInterval?: number;
/**
* max number of attempts to reconnect when websocket connection is dropped; default is 10
*/
reconnectMaxAttempts?: number;
/**
* enable testing of reconnection
*/
testReconnect?: boolean;
};
const UseStompNotificationsProvider: React.FC<UseStompNotificationsProviderProps> = React.memo(
({
authHeader,
headers,
reconnectInterval,
reconnectMaxAttempts,
testReconnect,
url,
...props
}) => {
const [connected, toggleConnected] = useToggle(false);
const worker = useMemo<WebSocketWorker>(
() =>
new WebSocketWorker({
onConnected: toggleConnected,
onDisconnected: toggleConnected,
reconnectInterval,
reconnectMaxAttempts,
url: url
}),
[]
);
useEffect(() => {
if (authHeader) {
worker.setAuthHeader(authHeader);
worker.connect();
}
}, [authHeader]);
useEffect(() => {
return () => {
worker.destroy();
};
}, []);
const ctx = useMemo(
() => ({
connected,
dismiss: worker.dismiss,
send: worker.send,
subscribe: worker.subscribe,
subscribeSync: worker.subscribeSync
}),
[
connected,
worker.dismiss,
worker.send,
worker.subscribe,
worker.subscribeSync
]
);
useEffect(() => {
if (connected && testReconnect) {
const timeout = setTimeout(() => {
worker.testDisconnect();
}, 10000);
return () => {
clearTimeout(timeout);
};
}
}, [connected, testReconnect]);
return (
<UseStompCtx.Provider value={ctx}>
<SnackbarProvider {...props}>{props.children}</SnackbarProvider>
</UseStompCtx.Provider>
);
}
);
UseStompNotificationsProvider.defaultProps = {
maxSnack: 3,
reconnectInterval: 10000,
reconnectMaxAttempts: 10
};
export default UseStompNotificationsProvider;