21357: favorites displays correct names Arvados-DCO-1.1-Signed-off-by: Lisa Knox...
[arvados.git] / services / workbench2 / src / common / link-update-name.ts
1 // Copyright (C) The Arvados Authors. All rights reserved.
2 //
3 // SPDX-License-Identifier: AGPL-3.0
4
5 import { LinkResource } from 'models/link';
6 import { Dispatch } from 'redux';
7 import { RootState } from 'store/store';
8 import { ServiceRepository } from 'services/services';
9 import { getResourceService } from 'services/services';
10 import { Resource, extractUuidKind } from 'models/resource';
11
12 type NameableResource = Resource & { name?: string };
13
14 export const verifyAndUpdateLinkName = async (link: LinkResource, dispatch: Dispatch, getState: () => RootState, services: ServiceRepository):Promise<string> => {
15   //check if head resource is already in the store
16     let headResource: Resource | undefined = getState().resources[link.headUuid];
17     if (!headResource) {
18         headResource = await fetchResource(link.headUuid)(dispatch, getState, services);
19         if(!headResource) {
20             console.error('Could not verify link', link);
21             return link.name;
22         }
23     }
24
25     if (validateLinkNameProp(link, headResource) === true) return link.name;
26
27     const updatedLink = updateLinkNameProp(link, headResource);
28
29     return updatedLink.name;
30 };
31
32 const fetchResource = (uuid: string, showErrors?: boolean) => async (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository) => {
33     try {
34         const kind = extractUuidKind(uuid);
35         const service = getResourceService(kind)(services);
36         if (service) {
37             const resource = await service.get(uuid, showErrors);
38             return resource;
39         }
40     } catch(e) {
41         console.error(e);
42     }
43     return undefined;
44 };
45
46 const validateLinkNameProp = (link: LinkResource, head: NameableResource) => {
47   if(!link.name || link.name !== head.name) return false;
48     return true;
49 };
50
51 const updateLinkNameProp = (link: LinkResource, head: NameableResource) => {
52   const updatedLink = {...link};
53   if(head.name) updatedLink.name = head.name;
54   return updatedLink;
55 }