-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathuseStompProvider.tsx
187 lines (165 loc) · 5.21 KB
/
useStompProvider.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
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
import React, {useCallback, useEffect, useMemo, useRef, useState} from 'react';
import SockJS, {Options} from 'sockjs-client';
import type {Client} from 'stompjs';
import UseStompCtx from './context';
import Stomp from './stomp';
export type UseStompProviderProps = {
/**
* HTTP to connect
*/
url: string;
/**
* Add console logs for debugging
*/
debug?: boolean;
/**
* SockJS Options (https://github.com/sockjs/sockjs-client#sockjs-client-api)
*/
options?: Options;
/**
* The request auth header will be passed to the server or agent through the STOMP connection frame
*/
authHeader?: string;
/**
* The request header will be passed to the server or agent through the STOMP connection frame
*/
headers?: Record<string, unknown>;
/**
* override default parsing of messages
*/
parseMessage?(channel: string, msg: any): any;
/**
* override default packaging of messages
*/
packageMessage?(channel: string, msg: any, optHeaders: any): any;
/**
* The request header that will be passed when subscribing to the target
*/
subscribeHeaders?: Record<string, unknown>;
};
export default React.memo<UseStompProviderProps>((props) => {
const client = useRef<Client>(null);
const [connected, setConnected] = useState(false);
const packageMessage = useCallback(
(channel, msg, optHeaders) => {
if (props.packageMessage) {
return props.packageMessage(channel, msg, optHeaders);
}
try {
return typeof msg === 'object' && msg !== null
? JSON.stringify(msg)
: msg;
} catch (e) {
return msg;
}
},
[props.packageMessage]
);
const parseMessage = useCallback(
(channel, msg) => {
if (props.parseMessage) {
return props.parseMessage(channel, msg);
}
try {
const parsed = JSON.parse(msg);
return typeof parsed === 'object' &&
parsed !== null &&
parsed.content
? parsed.content
: parsed;
} catch (e) {
return msg;
}
},
[props.parseMessage]
);
const onConnected = useCallback(() => {
console.log('%c[use-stomp::connected]', 'color: rgb(95,153,63);');
setConnected(() => true);
}, []);
const onDisconnected = useCallback(() => {
console.log('%c[use-stomp::disconnected]', 'color: rgb(170,34,23);');
setConnected(() => false);
client.current = null;
}, []);
const onError = useCallback((error) => {
console.error('[use-stomp::error]', error);
}, []);
const send = useCallback(
(channel, msg, optHeaders = {}) => {
if (connected) {
client.current.send(
channel,
optHeaders,
packageMessage(channel, msg, optHeaders)
);
} else {
console.warn(
'[use-stomp::send]',
'cannot send when websocket is not connected'
);
}
},
[client.current, connected, packageMessage]
);
const subscribe = useCallback(
(channel, callback) => {
try {
return client.current.subscribe(
channel,
(msg: any) => {
const body = parseMessage(channel, msg.body);
callback(body, msg.headers.destination);
if (body && body.status === 'END') {
(client.current.disconnect as any)();
}
},
props.subscribeHeaders
).unsubscribe;
} catch (e) {
throw Error(e);
}
},
[
client.current?.disconnect,
client.current?.subscribe,
parseMessage,
props.subscribeHeaders
]
);
useEffect(() => {
const hasHeaders = props.headers || props.authHeader;
if (hasHeaders && props.url && !connected) {
client.current = Stomp.over(
new SockJS(props.url, null, props.options),
!!props.debug
);
(client.current.connect as any)(
props.authHeader
? {Authorization: props.authHeader}
: props.headers,
onConnected,
onDisconnected,
onError
);
}
return () => {
if (connected && client.current) {
(client.current.disconnect as any)();
}
};
}, [connected, props.authHeader, props.headers, props.url]);
const ctx = useMemo(
() => ({
send,
subscribe,
connected
}),
[connected, send, subscribe]
);
return (
<UseStompCtx.Provider value={ctx}>
{props.children}
</UseStompCtx.Provider>
);
});