18966: Changes back collectionService.get() to use the GET HTTP method.
[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             params: {
122                 select: select
123                     ? `[${select.map(snakeCase).map(s => `"${s}"`).join(',')}]`
124                     : undefined
125             }
126         };
127         if (session) {
128             cfg.baseURL = session.baseUrl;
129             cfg.headers = { 'Authorization': 'Bearer ' + session.token };
130         }
131
132         return CommonService.defaultResponse(
133             this.serverApi
134                 .get<T>(`/${this.resourceType}/${uuid}`, cfg),
135             this.actions,
136             true, // mapKeys
137             showErrors
138         );
139     }
140
141     list(args: ListArguments = {}, showErrors?: boolean): Promise<ListResults<T>> {
142         const { filters, select, ...other } = args;
143         const params = {
144             ...CommonService.mapKeys(snakeCase)(other),
145             filters: filters ? `[${filters}]` : undefined,
146             select: select
147                 ? `[${select.map(snakeCase).map(s => `"${s}"`).join(', ')}]`
148                 : undefined
149         };
150
151         if (QueryString.stringify(params).length <= 1500) {
152             return CommonService.defaultResponse(
153                 this.serverApi.get(`/${this.resourceType}`, { params }),
154                 this.actions,
155                 showErrors
156             );
157         } else {
158             // Using the POST special case to avoid URI length 414 errors.
159             const formData = new FormData();
160             formData.append("_method", "GET");
161             Object.keys(params).forEach(key => {
162                 if (params[key] !== undefined) {
163                     formData.append(key, params[key]);
164                 }
165             });
166             return CommonService.defaultResponse(
167                 this.serverApi.post(`/${this.resourceType}`, formData, {
168                     params: {
169                         _method: 'GET'
170                     }
171                 }),
172                 this.actions,
173                 showErrors
174             );
175         }
176     }
177
178     update(uuid: string, data: Partial<T>) {
179         this.validateUuid(uuid);
180         return CommonService.defaultResponse(
181             this.serverApi
182                 .put<T>(`/${this.resourceType}/${uuid}`, data && CommonService.mapKeys(snakeCase)(data)),
183             this.actions
184         );
185     }
186 }