|
| 1 | +import { useEffect, useState } from "react"; |
| 2 | +import { WsHandler, createWsHandler, fetchBack, useConfig, useConnectionsStore, useFetchBack, useMeasurementsStore, usePodDataStore } from ".." |
| 3 | + |
| 4 | +type loadBackendResult = { |
| 5 | + state: "pending"; |
| 6 | +} | { |
| 7 | + state: "fulfilled"; |
| 8 | + wsHandler: WsHandler; |
| 9 | +} | { |
| 10 | + state: "rejected"; |
| 11 | + error: Error; |
| 12 | +}; |
| 13 | + |
| 14 | +type UseLoadBackend = (isProduction: boolean) => loadBackendResult; |
| 15 | + |
| 16 | +// Custom hook that initializes the Websocket connection, returning the WsHandler object |
| 17 | +// and fetches the podDataDescription from the server, initializing the PodData and Measurements in the store. |
| 18 | +export const useLoadBackend : UseLoadBackend = (isProduction) => { |
| 19 | + const config = useConfig(); |
| 20 | + const initPodData = usePodDataStore((state) => state.initPodData); |
| 21 | + const initMeasurements = useMeasurementsStore((state) => state.initMeasurements); |
| 22 | + const setBackendConnection = useConnectionsStore((state) => state.setBackendConnection); |
| 23 | + |
| 24 | + const [result, setResult] = useState<loadBackendResult>({state: "pending"}); |
| 25 | + |
| 26 | + const BACKEND_URL = isProduction |
| 27 | + ? `${config.prodServer.ip}:${config.prodServer.port}/${config.paths.websocket}` |
| 28 | + : `${config.devServer.ip}:${config.devServer.port}/${config.paths.websocket}`; |
| 29 | + |
| 30 | + const POD_DATA_DESCRIPTION_URL = isProduction |
| 31 | + ? `http://${config.prodServer.ip}:${config.prodServer.port}/${config.paths.podDataDescription}` |
| 32 | + : `http://${config.devServer.ip}:${config.devServer.port}/${config.paths.podDataDescription}`; |
| 33 | + |
| 34 | + useEffect(() => { |
| 35 | + Promise.all([ |
| 36 | + createWsHandler( |
| 37 | + BACKEND_URL, |
| 38 | + true, |
| 39 | + () => setBackendConnection(true), |
| 40 | + () => setBackendConnection(false) |
| 41 | + ), |
| 42 | + fetch(POD_DATA_DESCRIPTION_URL).then((res) => res.json()).then( |
| 43 | + (adapter) => { |
| 44 | + initPodData(adapter); |
| 45 | + initMeasurements(adapter); |
| 46 | + } |
| 47 | + ), |
| 48 | + ]) |
| 49 | + .then(result => setResult({state: "fulfilled", wsHandler: result[0]})) |
| 50 | + .catch(error => setResult({state: "rejected", error})); |
| 51 | + }, []); |
| 52 | + |
| 53 | + return result; |
| 54 | +} |
0 commit comments