bc24f22796b21001bce09b358e1efe6c657d6248
[arvados-workbench2.git] / src / services / common-service / common-resource-service.ts
1 // Copyright (C) The Arvados Authors. All rights reserved.
2 //
3 // SPDX-License-Identifier: AGPL-3.0
4
5 import { AxiosInstance } from "axios";
6 import { Resource } from "src/models/resource";
7 import { ApiActions } from "~/services/api/api-actions";
8 import { CommonService } from "~/services/common-service/common-service";
9
10 export enum CommonResourceServiceError {
11     UNIQUE_NAME_VIOLATION = 'UniqueNameViolation',
12     OWNERSHIP_CYCLE = 'OwnershipCycle',
13     MODIFYING_CONTAINER_REQUEST_FINAL_STATE = 'ModifyingContainerRequestFinalState',
14     NAME_HAS_ALREADY_BEEN_TAKEN = 'NameHasAlreadyBeenTaken',
15     UNKNOWN = 'Unknown',
16     NONE = 'None'
17 }
18
19 export class CommonResourceService<T extends Resource> extends CommonService<T> {
20     constructor(serverApi: AxiosInstance, resourceType: string, actions: ApiActions, readOnlyFields: string[] = []) {
21         super(serverApi, resourceType, actions, readOnlyFields.concat([
22             'uuid',
23             'etag',
24             'kind'
25         ]));
26     }
27
28     create(data?: Partial<T>) {
29         if (data !== undefined) {
30             this.readOnlyFields.forEach( field => delete data[field] );
31         }
32         return super.create(data);
33     }
34
35     update(uuid: string, data: Partial<T>) {
36         if (data !== undefined) {
37             this.readOnlyFields.forEach( field => delete data[field] );
38         }
39         return super.update(uuid, data);
40     }
41 }
42
43 export const getCommonResourceServiceError = (errorResponse: any) => {
44     if ('errors' in errorResponse && 'errorToken' in errorResponse) {
45         const error = errorResponse.errors.join('');
46         switch (true) {
47             case /UniqueViolation/.test(error):
48                 return CommonResourceServiceError.UNIQUE_NAME_VIOLATION;
49             case /ownership cycle/.test(error):
50                 return CommonResourceServiceError.OWNERSHIP_CYCLE;
51             case /Mounts cannot be modified in state 'Final'/.test(error):
52                 return CommonResourceServiceError.MODIFYING_CONTAINER_REQUEST_FINAL_STATE;
53             case /Name has already been taken/.test(error):
54                 return CommonResourceServiceError.NAME_HAS_ALREADY_BEEN_TAKEN;
55             default:
56                 return CommonResourceServiceError.UNKNOWN;
57         }
58     }
59     return CommonResourceServiceError.NONE;
60 };
61
62