8530f5cd380135948ff581dbd8abb3ed4b58fdc6
[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, getResourceService } from 'services/services';
9 import { Resource, extractUuidKind } from 'models/resource';
10
11 type NameableResource = Resource & { name?: string };
12
13 export const verifyAndUpdateLinkName = async (link: LinkResource, dispatch: Dispatch, getState: () => RootState, services: ServiceRepository):Promise<string> => {
14   //check if head resource is already in the store
15     let headResource: Resource | undefined = getState().resources[link.headUuid];
16     //if not, fetch it
17     if (!headResource) {
18         headResource = await fetchResource(link.headUuid)(dispatch, getState, services);
19         if(!headResource) {
20             console.error('Could not validate link', link, 'because link head', link.headUuid, 'is not available');
21             return link.name;
22         }
23     }
24
25     if (validateLinkNameProp(link, headResource) === true) return link.name;
26
27     const updatedLink = updateLinkNameProp(link, headResource);
28     updateRemoteLinkName(updatedLink)(dispatch, getState, services);
29     
30     return updatedLink.name;
31 };
32
33 const fetchResource = (uuid: string, showErrors?: boolean) => async (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository) => {
34     try {
35         const kind = extractUuidKind(uuid);
36         const service = getResourceService(kind)(services);
37         if (service) {
38             const resource = await service.get(uuid, showErrors);
39             return resource;
40         }
41     } catch(e) {
42         console.error(`Could not fetch resource ${uuid}`, e);
43     }
44     return undefined;
45 };
46
47 const validateLinkNameProp = (link: LinkResource, head: NameableResource) => {
48   if(!link.name || link.name !== head.name) return false;
49     return true;
50 };
51
52 const updateLinkNameProp = (link: LinkResource, head: NameableResource) => {
53   const updatedLink = {...link};
54   if(head.name) updatedLink.name = head.name;
55   return updatedLink;
56 }
57
58 const updateRemoteLinkName = (link: LinkResource) => async (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository) => {
59     try {
60         const kind = extractUuidKind(link.uuid);
61         const service = getResourceService(kind)(services);
62         if (service) {
63             service.update(link.uuid, {name: link.name});
64         }
65     } catch (error) {
66         console.error('Could not update link name', link, error);
67     }
68 };