Merge branch 'master'
[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 * as _ from "lodash";
6 import { AxiosInstance, AxiosPromise } from "axios";
7 import { Resource } from "src/models/resource";
8 import * as uuid from "uuid/v4";
9 import { ApiActions } from "~/services/api/api-actions";
10
11 export interface ListArguments {
12     limit?: number;
13     offset?: number;
14     filters?: string;
15     order?: string;
16     select?: string[];
17     distinct?: boolean;
18     count?: string;
19 }
20
21 export interface ListResults<T> {
22     kind: string;
23     offset: number;
24     limit: number;
25     items: T[];
26     itemsAvailable: number;
27 }
28
29 export interface Errors {
30     errors: string[];
31     errorToken: string;
32 }
33
34 export enum CommonResourceServiceError {
35     UNIQUE_VIOLATION = 'UniqueViolation',
36     OWNERSHIP_CYCLE = 'OwnershipCycle',
37     MODIFYING_CONTAINER_REQUEST_FINAL_STATE = 'ModifyingContainerRequestFinalState',
38     UNKNOWN = 'Unknown',
39     NONE = 'None'
40 }
41
42 export class CommonResourceService<T extends Resource> {
43
44     static mapResponseKeys = (response: { data: any }) =>
45         CommonResourceService.mapKeys(_.camelCase)(response.data)
46
47     static mapKeys = (mapFn: (key: string) => string) =>
48         (value: any): any => {
49             switch (true) {
50                 case _.isPlainObject(value):
51                     return Object
52                         .keys(value)
53                         .map(key => [key, mapFn(key)])
54                         .reduce((newValue, [key, newKey]) => ({
55                             ...newValue,
56                             [newKey]: CommonResourceService.mapKeys(mapFn)(value[key])
57                         }), {});
58                 case _.isArray(value):
59                     return value.map(CommonResourceService.mapKeys(mapFn));
60                 default:
61                     return value;
62             }
63         }
64
65     static defaultResponse<R>(promise: AxiosPromise<R>, actions: ApiActions): Promise<R> {
66         const reqId = uuid();
67         actions.progressFn(reqId, true);
68         return promise
69             .then(data => {
70                 actions.progressFn(reqId, false);
71                 return data;
72             })
73             .then(CommonResourceService.mapResponseKeys)
74             .catch(({ response }) => {
75                 actions.progressFn(reqId, false);
76                 const errors = CommonResourceService.mapResponseKeys(response) as Errors;
77                 actions.errorFn(reqId, errors);
78                 throw errors;
79             });
80     }
81
82     protected serverApi: AxiosInstance;
83     protected resourceType: string;
84     protected actions: ApiActions;
85
86     constructor(serverApi: AxiosInstance, resourceType: string, actions: ApiActions) {
87         this.serverApi = serverApi;
88         this.resourceType = '/' + resourceType + '/';
89         this.actions = actions;
90     }
91
92     create(data?: Partial<T>) {
93         return CommonResourceService.defaultResponse(
94             this.serverApi
95                 .post<T>(this.resourceType, data && CommonResourceService.mapKeys(_.snakeCase)(data)),
96             this.actions
97         );
98     }
99
100     delete(uuid: string): Promise<T> {
101         return CommonResourceService.defaultResponse(
102             this.serverApi
103                 .delete(this.resourceType + uuid),
104             this.actions
105         );
106     }
107
108     get(uuid: string) {
109         return CommonResourceService.defaultResponse(
110             this.serverApi
111                 .get<T>(this.resourceType + uuid),
112             this.actions
113         );
114     }
115
116     list(args: ListArguments = {}): Promise<ListResults<T>> {
117         const { filters, order, ...other } = args;
118         const params = {
119             ...other,
120             filters: filters ? `[${filters}]` : undefined,
121             order: order ? order : undefined
122         };
123         return CommonResourceService.defaultResponse(
124             this.serverApi
125                 .get(this.resourceType, {
126                     params: CommonResourceService.mapKeys(_.snakeCase)(params)
127                 }),
128             this.actions
129         );
130     }
131
132     update(uuid: string, data: Partial<T>) {
133         return CommonResourceService.defaultResponse(
134             this.serverApi
135                 .put<T>(this.resourceType + uuid, data && CommonResourceService.mapKeys(_.snakeCase)(data)),
136             this.actions
137         );
138     }
139 }
140
141 export const getCommonResourceServiceError = (errorResponse: any) => {
142     if ('errors' in errorResponse && 'errorToken' in errorResponse) {
143         const error = errorResponse.errors.join('');
144         switch (true) {
145             case /UniqueViolation/.test(error):
146                 return CommonResourceServiceError.UNIQUE_VIOLATION;
147             case /ownership cycle/.test(error):
148                 return CommonResourceServiceError.OWNERSHIP_CYCLE;
149             case /Mounts cannot be modified in state 'Final'/.test(error):
150                 return CommonResourceServiceError.MODIFYING_CONTAINER_REQUEST_FINAL_STATE;
151             default:
152                 return CommonResourceServiceError.UNKNOWN;
153         }
154     }
155     return CommonResourceServiceError.NONE;
156 };
157
158