import { configApiRef , errorApiRef , useApi } from '@backstage/core-plugin-api' ; import { useAsyncRetry } from 'react-use' ; import { argoCDApiRef } from '../api' ; export const useAppDetails = ( { appName , appSelector , projectName , url , } ) => { const api = useApi ( argoCDApiRef ) ; const errorApi = useApi ( errorApiRef ) ; const configApi = useApi ( configApiRef ) ; const { loading , value , error , retry } = useAsyncRetry ( async ( ) => { const argoSearchMethod = Boolean ( configApi . getOptionalConfigArray ( 'argocd.appLocatorMethods' ) ?. length ) ; try { if ( ! argoSearchMethod && appName ) { return await api . getAppDetails ( { url , appName } ) ; } if ( argoSearchMethod && appName ) { const kubeInfo = await api . serviceLocatorUrl ( { appName : appName as string , } ) ; if ( kubeInfo instanceof Error ) return kubeInfo ; const promises = kubeInfo . map ( async ( instance ) => { const apiOut = await api . getAppDetails ( { url , appName , instance : instance . name , } ) ; if ( ! apiOut . metadata ) { return { status : { history : [ ] , sync : { status : 'Missing' } , health : { status : 'Missing' } , operationState : { } , } , metadata : { name : appName , instance : instance . name } , } ; } apiOut . metadata . instance = instance ; return apiOut ; } ) ; return await Promise . all ( promises ) ; } if ( argoSearchMethod && appSelector ) { const kubeInfo = await api . serviceLocatorUrl ( { appSelector : appSelector as string , } ) ; if ( kubeInfo instanceof Error ) return kubeInfo ; const promises = kubeInfo . map ( async ( instance ) => { const apiOut = await api . getAppListDetails ( { url , appSelector , instance : instance . name , } ) ; return apiOut ; } ) ; const output = await Promise . all ( promises ) ; const items = { items : output . flatMap ( argoCdAppList => argoCdAppList . items ) . filter ( item => item !== null ) , } ; return items ; } if ( appSelector || projectName ) { return await api . listApps ( { url , appSelector , projectName } ) ; } return Promise . reject ( 'Neither appName nor appSelector provided' ) ; } catch ( e ) { errorApi . post ( new Error ( 'Something went wrong' ) ) ; return Promise . reject ( e ) ; } } ) ; return { loading , value , error , retry , } ; } ;