-
-
Notifications
You must be signed in to change notification settings - Fork 206
/
Copy pathHealthContext.tsx
101 lines (90 loc) · 2.94 KB
/
HealthContext.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
import React, { useCallback, useState } from 'react';
import Electron from 'electron';
import { transformData } from './helpers';
const { ipcRenderer } = window.require('electron');
export const HealthContext = React.createContext<any>(null);
/**
* MANAGES THE FOLLOWING DATA AND ACTIONS:
* @property {Object} healthData
* @method setServices
* @method setHealthData
* @method fetchHealthData
*/
interface Props {
children: any;
}
const HealthContextProvider: React.FC<Props> = React.memo(({ children }) => {
const [healthData, setHealthData] = useState<any>({ healthDataList: [], healthTimeList: [] });
const [services, setServices] = useState<Array<string>>([]);
function tryParseJSON(jsonString: any) {
try {
const o = JSON.parse(jsonString);
if (o && typeof o === 'object') {
return o;
}
} catch (e) {
let errorString = 'Not valid JSON: ' + e.message;
console.log(errorString);
new Error(errorString);
}
return false;
}
/**
* @function fetchEventData - sending a request to the backend to retrieve data.
* Data is then parsed and the setHealthData is then set.
*/
const fetchHealthData = useCallback(serv => {
ipcRenderer.removeAllListeners('healthResponse');
let temp: string[] = [];
console.log('the cb being passed into fetch health data from graphscontainer is: ', serv);
Promise.all(
serv.map((service: string) => {
return new Promise((resolve, reject) => {
ipcRenderer.send('healthRequest', service);
ipcRenderer.on('healthResponse', (event: Electron.Event, data: string) => {
let result: any[];
if (JSON.stringify(data) !== '{}' && tryParseJSON(data)) {
result = JSON.parse(data);
console.log('the health results before transformation: ', result)
if (result && result.length && service === Object.keys(result[0])[0]) {
resolve(result[0]);
}
}
});
}).then((dt: any) => {
temp.push(dt);
if (checkServicesComplete(temp, serv)) {
setServices(serv);
let transformedData: any = {};
transformedData = transformData(temp);
console.log('results from fetch health data: ', transformedData);
setHealthData(transformedData);
}
});
})
);
}, []);
const checkServicesComplete = (temp: any[], serv: string[]) => {
if (temp.length !== serv.length) {
return false;
}
const arr1: string[] = [];
for (let i = 0; i < temp.length; i++) {
arr1.push(Object.keys(temp[i])[0]);
}
return arr1.sort().toString() === serv.sort().toString();
};
return (
<HealthContext.Provider
value={{
setHealthData,
fetchHealthData,
healthData,
services,
}}
>
{children}
</HealthContext.Provider>
);
});
export default HealthContextProvider;