ddaf2ab02fa5ee4e18d544158e42f7606339983c
[arvados-workbench2.git] / src / services / common-service / common-service.ts
1 // Copyright (C) The Arvados Authors. All rights reserved.
2 //
3 // SPDX-License-Identifier: AGPL-3.0
4
5 import { camelCase, isPlainObject, isArray, snakeCase } from "lodash";
6 import { AxiosInstance, AxiosPromise, AxiosRequestConfig } from "axios";
7 import uuid from "uuid/v4";
8 import { ApiActions } from "services/api/api-actions";
9 import QueryString from "query-string";
10 import { Session } from "models/session";
11
12 interface Errors {
13     status: number;
14     errors: string[];
15     errorToken: string;
16 }
17
18 export interface ListArguments {
19     limit?: number;
20     offset?: number;
21     filters?: string;
22     order?: string;
23     select?: string[];
24     distinct?: boolean;
25     count?: string;
26     includeOldVersions?: boolean;
27 }
28
29 export interface ListResults<T> {
30     clusterId?: string;
31     kind: string;
32     offset: number;
33     limit: number;
34     items: T[];
35     itemsAvailable: number;
36 }
37
38 export class CommonService<T> {
39     protected serverApi: AxiosInstance;
40     protected resourceType: string;
41     protected actions: ApiActions;
42     protected readOnlyFields: string[];
43
44     constructor(serverApi: AxiosInstance, resourceType: string, actions: ApiActions, readOnlyFields: string[] = []) {
45         this.serverApi = serverApi;
46         this.resourceType = resourceType;
47         this.actions = actions;
48         this.readOnlyFields = readOnlyFields;
49     }
50
51     static mapResponseKeys = (response: { data: any }) =>
52         CommonService.mapKeys(camelCase)(response.data)
53
54     static mapKeys = (mapFn: (key: string) => string) =>
55         (value: any): any => {
56             switch (true) {
57                 case isPlainObject(value):
58                     return Object
59                         .keys(value)
60                         .map(key => [key, mapFn(key)])
61                         .reduce((newValue, [key, newKey]) => ({
62                             ...newValue,
63                             [newKey]: (key === 'items') ? CommonService.mapKeys(mapFn)(value[key]) : value[key]
64                         }), {});
65                 case isArray(value):
66                     return value.map(CommonService.mapKeys(mapFn));
67                 default:
68                     return value;
69             }
70         }
71
72     protected validateUuid(uuid: string) {
73         if (uuid === "") {
74             throw new Error('UUID cannot be empty string');
75         }
76     }
77
78     static defaultResponse<R>(promise: AxiosPromise<R>, actions: ApiActions, mapKeys = true, showErrors = true): Promise<R> {
79         const reqId = uuid();
80         actions.progressFn(reqId, true);
81         return promise
82             .then(data => {
83                 actions.progressFn(reqId, false);
84                 return data;
85             })
86             .then((response: { data: any }) => {
87                 return mapKeys ? CommonService.mapResponseKeys(response) : response.data;
88             })
89             .catch(({ response }) => {
90                 actions.progressFn(reqId, false);
91                 const errors = CommonService.mapResponseKeys(response) as Errors;
92                 errors.status = response.status;
93                 actions.errorFn(reqId, errors, showErrors);
94                 throw errors;
95             });
96     }
97
98     create(data?: Partial<T>, showErrors?: boolean) {
99         return CommonService.defaultResponse(
100             this.serverApi
101                 .post<T>(`/${this.resourceType}`, data && CommonService.mapKeys(snakeCase)(data)),
102             this.actions,
103             true, // mapKeys
104             showErrors
105         );
106     }
107
108     delete(uuid: string): Promise<T> {
109         this.validateUuid(uuid);
110         return CommonService.defaultResponse(
111             this.serverApi
112                 .delete(`/${this.resourceType}/${uuid}`),
113             this.actions
114         );
115     }
116
117     get(uuid: string, showErrors?: boolean, select?: string[], session?: Session) {
118         this.validateUuid(uuid);
119
120         const cfg: AxiosRequestConfig = {};
121         if (session) {
122             cfg.baseURL = session.baseUrl;
123             cfg.headers = { 'Authorization': 'Bearer ' + session.token };
124         }
125
126         return CommonService.defaultResponse(
127             this.serverApi
128                 .get<T>(`/${this.resourceType}/${uuid}`, session ? cfg : undefined),
129             this.actions,
130             true, // mapKeys
131             showErrors
132         );
133     }
134
135     list(args: ListArguments = {}, showErrors?: boolean): Promise<ListResults<T>> {
136         const { filters, select, ...other } = args;
137         const params = {
138             ...CommonService.mapKeys(snakeCase)(other),
139             filters: filters ? `[${filters}]` : undefined,
140             select: select
141                 ? `[${select.map(snakeCase).map(s => `"${s}"`).join(', ')}]`
142                 : undefined
143         };
144
145         if (QueryString.stringify(params).length <= 1500) {
146             return CommonService.defaultResponse(
147                 this.serverApi.get(`/${this.resourceType}`, { params }),
148                 this.actions,
149                 showErrors
150             );
151         } else {
152             // Using the POST special case to avoid URI length 414 errors.
153             const formData = new FormData();
154             formData.append("_method", "GET");
155             Object.keys(params).forEach(key => {
156                 if (params[key] !== undefined) {
157                     formData.append(key, params[key]);
158                 }
159             });
160             return CommonService.defaultResponse(
161                 this.serverApi.post(`/${this.resourceType}`, formData, {
162                     params: {
163                         _method: 'GET'
164                     }
165                 }),
166                 this.actions,
167                 showErrors
168             );
169         }
170     }
171
172     update(uuid: string, data: Partial<T>) {
173         this.validateUuid(uuid);
174         return CommonService.defaultResponse(
175             this.serverApi
176                 .put<T>(`/${this.resourceType}/${uuid}`, data && CommonService.mapKeys(snakeCase)(data)),
177             this.actions
178         );
179     }
180 }