-
Notifications
You must be signed in to change notification settings - Fork 20
/
Copy pathuseLogsStream.ts
53 lines (43 loc) · 1.45 KB
/
useLogsStream.ts
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
import {useEffect, useState} from 'react';
import {useAsync} from 'react-use';
import useWebSocket from 'react-use-websocket';
import {useWsEndpoint} from '@services/apiEndpoint';
import {getRtkIdToken} from '@utils/rtk';
export const useLogsStream = (executionId?: string, enabled?: boolean) => {
const wsRoot = useWsEndpoint();
const [logs, setLogs] = useState('');
// TODO: Consider getting token different way than using the one from RTK
const {value: token, loading: tokenLoading} = useAsync(getRtkIdToken);
useWebSocket(
`${wsRoot}/executions/${executionId}/logs/stream`,
{
onMessage: e => {
const logData = e.data;
setLogs(prev => {
if (prev) {
try {
const dataToJSON = JSON.parse(logData);
const potentialOutput = dataToJSON?.result?.output || dataToJSON?.output;
if (potentialOutput) {
return potentialOutput;
}
return `${prev}\n${dataToJSON.content}`;
} catch (err) {
// It may be just an output directly, so we have to ignore it
}
return `${prev}\n${logData}`;
}
return `${logData}`;
});
},
shouldReconnect: () => true,
retryOnError: true,
queryParams: token ? {token} : {},
},
Boolean(executionId) && enabled && !tokenLoading
);
useEffect(() => {
setLogs('');
}, [executionId]);
return logs;
};