Merge branch 'master' into 14566-admin-modal
[arvados-workbench2.git] / src / services / ancestors-service / ancestors-service.ts
1 // Copyright (C) The Arvados Authors. All rights reserved.
2 //
3 // SPDX-License-Identifier: AGPL-3.0
4
5 import { GroupsService } from "~/services/groups-service/groups-service";
6 import { UserService } from '../user-service/user-service';
7 import { GroupResource } from '~/models/group';
8 import { UserResource } from '~/models/user';
9 import { extractUuidObjectType, ResourceObjectType } from "~/models/resource";
10
11 export class AncestorService {
12     constructor(
13         private groupsService: GroupsService,
14         private userService: UserService
15     ) { }
16
17     async ancestors(startUuid: string, endUuid: string): Promise<Array<UserResource | GroupResource>> {
18         return this._ancestors(startUuid, endUuid);
19     }
20
21     private async _ancestors(startUuid: string, endUuid: string, previousUuid = ''): Promise<Array<UserResource | GroupResource>> {
22
23         if (startUuid === previousUuid) {
24             return [];
25         }
26
27         const service = this.getService(extractUuidObjectType(startUuid));
28         if (service) {
29             try {
30                 const resource = await service.get(startUuid);
31                 if (startUuid === endUuid) {
32                     return [resource];
33                 } else {
34                     return [
35                         ...await this._ancestors(resource.ownerUuid, endUuid, startUuid),
36                         resource
37                     ];
38                 }
39             } catch (e) {
40                 return [];
41             }
42         } else {
43             return [];
44         }
45     }
46
47     private getService = (objectType?: string) => {
48         switch (objectType) {
49             case ResourceObjectType.GROUP:
50                 return this.groupsService;
51             case ResourceObjectType.USER:
52                 return this.userService;
53             default:
54                 return undefined;
55         }
56     }
57 }