blob: 44d54c0a3b4b33812d5ec4ca7153dd217763ab38 [file] [log] [blame]
Issam E. Maghni09a3a1f2022-11-02 04:56:21 +00001/*
2 * Copyright (C) 2022 Savoir-faire Linux Inc.
3 *
4 * This program is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU Affero General Public License as
6 * published by the Free Software Foundation; either version 3 of the
7 * License, or (at your option) any later version.
8 *
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU Affero General Public License for more details.
13 *
14 * You should have received a copy of the GNU Affero General Public
15 * License along with this program. If not, see
16 * <https://www.gnu.org/licenses/>.
17 */
idillondfb9f1f2023-01-23 10:32:51 -050018import { createContext, useEffect, useMemo, useRef } from 'react';
Issam E. Maghni09a3a1f2022-11-02 04:56:21 +000019
idillondfb9f1f2023-01-23 10:32:51 -050020import { WebSocketClient } from '../services/WebSocketClient';
Issam E. Maghni09a3a1f2022-11-02 04:56:21 +000021import { apiUrl } from '../utils/constants';
22import { WithChildren } from '../utils/utils';
23import { useAuthContext } from './AuthProvider';
24
Issam E. Maghni0432cb72022-11-12 06:09:26 +000025export interface IWebSocketContext {
idillondfb9f1f2023-01-23 10:32:51 -050026 bind: WebSocketClient['bind'];
27 unbind: WebSocketClient['unbind'];
28 send: WebSocketClient['send'];
Issam E. Maghni09a3a1f2022-11-02 04:56:21 +000029}
30
31export const WebSocketContext = createContext<IWebSocketContext | undefined>(undefined);
32
33export default ({ children }: WithChildren) => {
idillondfb9f1f2023-01-23 10:32:51 -050034 const webSocketClientRef = useRef<WebSocketClient>(new WebSocketClient());
Issam E. Maghni09a3a1f2022-11-02 04:56:21 +000035
36 const { token: accessToken } = useAuthContext();
37
idillondfb9f1f2023-01-23 10:32:51 -050038 useEffect(() => {
39 webSocketClientRef.current.connect(apiUrl, accessToken);
Issam E. Maghni0432cb72022-11-12 06:09:26 +000040 }, [accessToken]);
Issam E. Maghni09a3a1f2022-11-02 04:56:21 +000041
simon90efa042022-11-29 17:17:23 -050042 const value: IWebSocketContext = useMemo(
43 () => ({
idillondfb9f1f2023-01-23 10:32:51 -050044 bind: webSocketClientRef.current.bind.bind(webSocketClientRef.current),
45 unbind: webSocketClientRef.current.unbind.bind(webSocketClientRef.current),
46 send: webSocketClientRef.current.send.bind(webSocketClientRef.current),
simon90efa042022-11-29 17:17:23 -050047 }),
idillondfb9f1f2023-01-23 10:32:51 -050048 []
simon90efa042022-11-29 17:17:23 -050049 );
simonf929a362022-11-18 16:53:45 -050050
idillondfb9f1f2023-01-23 10:32:51 -050051 return <WebSocketContext.Provider value={value}>{children}</WebSocketContext.Provider>;
Issam E. Maghni09a3a1f2022-11-02 04:56:21 +000052};