From 88bd7ef966ede89bffde162343a886499b759f85 Mon Sep 17 00:00:00 2001 From: mufaddal motiwala Date: Mon, 13 Dec 2021 11:30:57 +0530 Subject: [PATCH] add a function for fetching user owned entities Signed-off-by: mufaddal motiwala --- .../OwnedEntityPicker/useOwnedEntities.ts | 60 +++++++++++++++++++ 1 file changed, 60 insertions(+) create mode 100644 plugins/scaffolder/src/components/fields/OwnedEntityPicker/useOwnedEntities.ts diff --git a/plugins/scaffolder/src/components/fields/OwnedEntityPicker/useOwnedEntities.ts b/plugins/scaffolder/src/components/fields/OwnedEntityPicker/useOwnedEntities.ts new file mode 100644 index 0000000000..ecdfc5c90f --- /dev/null +++ b/plugins/scaffolder/src/components/fields/OwnedEntityPicker/useOwnedEntities.ts @@ -0,0 +1,60 @@ +/* + * Copyright 2021 The Backstage Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { + catalogApiRef, + loadCatalogOwnerRefs, + loadIdentityOwnerRefs, +} from '@backstage/plugin-catalog-react'; +import { identityApiRef, useApi } from '@backstage/core-plugin-api'; +import { Entity, RELATION_OWNED_BY } from '@backstage/catalog-model'; +import { CatalogListResponse } from '@backstage/catalog-client'; +import { useAsync } from 'react-use'; +import { useMemo } from 'react'; + +export function useOwnedEntities(allowedKinds?: string[]): { + loading: boolean; + ownedEntities: CatalogListResponse | undefined; +} { + const identityApi = useApi(identityApiRef); + const catalogApi = useApi(catalogApiRef); + + const { loading, value: refs } = useAsync(async () => { + const identityRefs = await loadIdentityOwnerRefs(identityApi); + const catalogRefs = await loadCatalogOwnerRefs(catalogApi, identityRefs); + const catalogs = await catalogApi.getEntities( + allowedKinds + ? { + filter: { + kind: allowedKinds, + [`relations.${RELATION_OWNED_BY}`]: + [...identityRefs, ...catalogRefs] || [], + }, + } + : { + filter: { + [`relations.${RELATION_OWNED_BY}`]: + [...identityRefs, ...catalogRefs] || [], + }, + }, + ); + return catalogs; + }, []); + const ownedEntities = useMemo(() => { + return refs; + }, [refs]); + + return useMemo(() => ({ loading, ownedEntities }), [loading, ownedEntities]); +}