github.com/turbot/steampipe@v1.7.0-rc.0.0.20240517123944-7cef272d4458/ui/dashboard/src/hooks/useDashboardWebSocketEventHandler.ts (about) 1 import { DashboardActions, ReceivedSocketMessagePayload } from "../types"; 2 import { useCallback, useEffect, useRef } from "react"; 3 4 const useDashboardWebSocketEventHandler = (dispatch, eventHooks) => { 5 const controlEventBuffer = useRef<ReceivedSocketMessagePayload[]>([]); 6 const leafNodesCompletedEventBuffer = useRef<ReceivedSocketMessagePayload[]>( 7 [] 8 ); 9 const leafNodesUpdatedEventBuffer = useRef<ReceivedSocketMessagePayload[]>( 10 [] 11 ); 12 13 const eventHandler = useCallback( 14 (event: ReceivedSocketMessagePayload) => { 15 switch (event.action) { 16 case DashboardActions.CONTROL_COMPLETE: 17 case DashboardActions.CONTROL_ERROR: 18 controlEventBuffer.current.push(event); 19 break; 20 case DashboardActions.LEAF_NODE_COMPLETE: 21 leafNodesCompletedEventBuffer.current.push({ 22 ...event, 23 timestamp: new Date().toISOString(), 24 }); 25 break; 26 case DashboardActions.LEAF_NODE_UPDATED: 27 leafNodesUpdatedEventBuffer.current.push(event); 28 break; 29 default: 30 dispatch({ 31 type: event.action, 32 ...event, 33 }); 34 } 35 36 const hookHandler = eventHooks && eventHooks[event.action]; 37 if (hookHandler) { 38 hookHandler(event); 39 } 40 }, 41 [dispatch, eventHooks] 42 ); 43 44 useEffect(() => { 45 const interval = setInterval(() => { 46 if ( 47 controlEventBuffer.current.length === 0 && 48 leafNodesCompletedEventBuffer.current.length === 0 && 49 leafNodesUpdatedEventBuffer.current.length === 0 50 ) { 51 return; 52 } 53 const controlEventsToProcess = [...controlEventBuffer.current]; 54 const leafNodeCompletedEventsToProcess = [ 55 ...leafNodesCompletedEventBuffer.current, 56 ]; 57 const leafNodeUpdatedEventsToProcess = [ 58 ...leafNodesUpdatedEventBuffer.current, 59 ]; 60 controlEventBuffer.current = []; 61 leafNodesCompletedEventBuffer.current = []; 62 leafNodesUpdatedEventBuffer.current = []; 63 if (controlEventsToProcess.length > 0) { 64 dispatch({ 65 type: DashboardActions.CONTROLS_UPDATED, 66 controls: controlEventsToProcess, 67 }); 68 } 69 if (leafNodeCompletedEventsToProcess.length > 0) { 70 dispatch({ 71 type: DashboardActions.LEAF_NODES_COMPLETE, 72 nodes: leafNodeCompletedEventsToProcess, 73 }); 74 } 75 if (leafNodeUpdatedEventsToProcess.length > 0) { 76 dispatch({ 77 type: DashboardActions.LEAF_NODES_UPDATED, 78 nodes: leafNodeUpdatedEventsToProcess, 79 }); 80 } 81 }, 500); 82 return () => clearInterval(interval); 83 }, [dispatch]); 84 85 return { eventHandler }; 86 }; 87 88 export default useDashboardWebSocketEventHandler;