import { useEffect , useState , useMemo } from 'react' ; import useAttempt from 'shared/hooks/useAttemptNext' ; import Ctx from 'teleport/teleportContext' ; import { getRangeOptions , EventRange , } from 'teleport/components/EventRangePicker' ; import { Event , EventCode , formatters } from 'teleport/services/audit' ; export default function useAuditEvents ( ctx , clusterId , eventCode ? ) { const rangeOptions = useMemo ( ( ) => getRangeOptions ( ) , [ ] ) ; const [ range , setRange ] = useState < EventRange > ( rangeOptions [ 0 ] ) ; const { attempt , setAttempt , run } = useAttempt ( 'processing' ) ; const [ results , setResults ] = useState < EventResult > ( { events : [ ] , fetchStartKey : '' , fetchStatus : '' , } ) ; const filterBy = eventCode ? formatters [ eventCode ] . type : '' ; useEffect ( ( ) => { fetch ( ) ; } , [ clusterId , range ] ) ; function fetchMore ( ) { setResults ( { ... results , fetchStatus : 'loading' , } ) ; ctx . auditService . fetchEvents ( clusterId , { ... range , filterBy , startKey : results . fetchStartKey , } ) . then ( res => setResults ( { events : [ ... results . events , ... res . events ] , fetchStartKey : res . startKey , fetchStatus : res . startKey ? '' : 'disabled' , } ) ) . catch ( ( err ) => { setAttempt ( { status : 'failed' , statusText : err . message } ) ; } ) ; } function fetch ( ) { run ( ( ) => ctx . auditService . fetchEvents ( clusterId , { ... range , filterBy , } ) . then ( res => setResults ( { events : res . events , fetchStartKey : res . startKey , fetchStatus : res . startKey ? '' : 'disabled' , } ) ) ) ; } return { ... results , fetchMore , clusterId , attempt , range , setRange , rangeOptions , } ; } type EventResult = { events : Event [ ] ; fetchStatus : 'loading' | 'disabled' | '' ; fetchStartKey : string ; } ; export type State = ReturnType < typeof useAuditEvents > ;