Created
August 14, 2024 09:15
-
-
Save AndrienkoAleksandr/827094c8d7ebc3179b8350e8b21aa61f to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React, { createContext, useContext, useMemo } from 'react'; | |
import useAsyncFn from 'react-use/lib/useAsyncFn'; | |
import useDebounce from 'react-use/lib/useDebounce'; | |
import { useApi } from '@backstage/core-plugin-api'; | |
import { ErrorResponseBody } from '@backstage/errors'; | |
import { useEntity } from '@backstage/plugin-catalog-react'; | |
import { | |
ANNOTATION_PROVIDER_ID, | |
Cluster, | |
} from '@janus-idp/backstage-plugin-ocm-common'; | |
import { OcmApiRef } from '../../api'; | |
type ClusterContextType = { | |
data: Cluster | null; | |
loading: boolean; | |
error: Error | null; | |
}; | |
const ClusterContext = createContext<ClusterContextType>( | |
{} as ClusterContextType, | |
); | |
export const ClusterContextProvider = (props: any) => { | |
const { entity } = useEntity(); | |
const ocmApi = useApi(OcmApiRef); | |
const providerId = entity.metadata.annotations![ANNOTATION_PROVIDER_ID]; | |
if (!providerId) { | |
return <></>; | |
} | |
const [{ value: cluster, loading, error: asyncError }, refresh] = useAsyncFn( | |
async () => { | |
const cl = await ocmApi.getClusterByName( | |
providerId, | |
entity.metadata.name, | |
); | |
return cl; | |
}, | |
[], | |
{ loading: true }, | |
); | |
useDebounce(refresh, 10); | |
const isError = Boolean(asyncError || (cluster && 'error' in cluster)); | |
const error = isError | |
? asyncError || | |
Object.assign(new Error((cluster as ErrorResponseBody)?.error?.message), { | |
...(cluster as ErrorResponseBody)?.error, | |
}) | |
: null; | |
const value = useMemo( | |
() => ({ | |
data: isError || loading ? null : (cluster as Cluster), | |
loading, | |
error, | |
}), | |
[cluster, isError, loading, error], | |
); | |
return ( | |
<ClusterContext.Provider value={value}> | |
{props.children} | |
</ClusterContext.Provider> | |
); | |
}; | |
export const useCluster = () => useContext(ClusterContext); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment