Merge branch '21621-io-panel-json-tab-copy' into main. Closes #21621
[arvados.git] / services / workbench2 / src / store / resources / resources.ts
1 // Copyright (C) The Arvados Authors. All rights reserved.
2 //
3 // SPDX-License-Identifier: AGPL-3.0
4
5 import { Resource, EditableResource } from "models/resource";
6 import { ResourceKind } from 'models/resource';
7 import { GroupResource } from "models/group";
8
9 export type ResourcesState = { [key: string]: Resource };
10
11 export const getResourceWithEditableStatus = <T extends GroupResource & EditableResource>(id: string, userUuid?: string) =>
12     (state: ResourcesState): T | undefined => {
13         if (state[id] === undefined) { return; }
14
15         const resource = JSON.parse(JSON.stringify(state[id])) as T;
16
17         if (resource) {
18             if (resource.canWrite === undefined) {
19                 resource.isEditable = (state[resource.ownerUuid] as GroupResource)?.canWrite;
20             } else {
21                 resource.isEditable = resource.canWrite;
22             }
23         }
24
25         return resource;
26     };
27
28 export const getResource = <T extends Resource = Resource>(id: string) =>
29     (state: ResourcesState): T | undefined =>
30         state[id] as T;
31
32 export const setResource = <T extends Resource>(id: string, data: T) =>
33     (state: ResourcesState) => ({
34         ...state,
35         [id]: data
36     });
37
38 export const deleteResource = (id: string) =>
39     (state: ResourcesState) => {
40         const newState = { ...state };
41         delete newState[id];
42         return newState;
43     };
44
45 export const filterResources = (filter: (resource: Resource) => boolean) =>
46     (state: ResourcesState) =>
47         Object
48             .keys(state)
49             .reduce((resources, id) => {
50                 const resource = getResource(id)(state);
51                 return resource
52                     ? [...resources, resource]
53                     : resources;
54             }, [])
55             .filter(filter);
56
57 export const filterResourcesByKind = (kind: ResourceKind) =>
58     (state: ResourcesState) =>
59         filterResources(resource => resource.kind === kind)(state);