import { i18n } from '@kbn/i18n' ; import { useQuery } from 'react-query' ; import { GetAgentsResponse } from '../../../fleet/common' ; import { useErrorToast } from '../common/hooks/use_error_toast' ; import { useKibana } from '../common/lib/kibana' ; interface UseAllAgents { osqueryPolicies : string [ ] ; osqueryPoliciesLoading : boolean ; } interface RequestOptions { perPage ? : number ; page ? : number ; } export const useAllAgents = ( { osqueryPolicies , osqueryPoliciesLoading } , searchValue = '' , opts = { perPage : 9000 } ) => { const { perPage } = opts ; const { http } = useKibana ( ) . services ; const setErrorToast = useErrorToast ( ) ; return useQuery < GetAgentsResponse > ( [ 'agents' , osqueryPolicies , searchValue , perPage ] , ( ) => { let kuery = `(${ osqueryPolicies . map ( ( p ) => `policy_id:${ p }` ) . join ( ' or ' ) })` ; if ( searchValue ) { kuery += ` and (local_metadata.host.hostname:*${ searchValue }* or local_metadata.elastic.agent.id:*${ searchValue }*)` ; } return http . get ( `/internal/osquery/fleet_wrapper/agents` , { query : { kuery , perPage , } , } ) ; } , { select : ( data ) => data ?. agents || [ ] , enabled : ! osqueryPoliciesLoading && osqueryPolicies . length > 0 , onSuccess : ( ) => setErrorToast ( ) , onError : ( error ) => setErrorToast ( error ?. body , { title : i18n . translate ( 'xpack.osquery.agents.fetchError' , { defaultMessage : 'Error while fetching agents' , } ) , toastMessage : error ?. body ?. error , } ) , } ) ; } ;