1 // Copyright (C) The Arvados Authors. All rights reserved.
3 // SPDX-License-Identifier: AGPL-3.0
5 import * as _ from "lodash";
6 import { AxiosInstance, AxiosPromise } from "axios";
7 import * as uuid from "uuid/v4";
8 import { ApiActions } from "~/services/api/api-actions";
9 import * as QueryString from "query-string";
16 export interface ListArguments {
26 export interface ListResults<T> {
32 itemsAvailable: number;
35 export class CommonService<T> {
36 protected serverApi: AxiosInstance;
37 protected resourceType: string;
38 protected actions: ApiActions;
40 constructor(serverApi: AxiosInstance, resourceType: string, actions: ApiActions) {
41 this.serverApi = serverApi;
42 this.resourceType = '/' + resourceType;
43 this.actions = actions;
46 static mapResponseKeys = (response: { data: any }) =>
47 CommonService.mapKeys(_.camelCase)(response.data)
49 static mapKeys = (mapFn: (key: string) => string) =>
50 (value: any): any => {
52 case _.isPlainObject(value):
55 .map(key => [key, mapFn(key)])
56 .reduce((newValue, [key, newKey]) => ({
58 [newKey]: (key === 'items') ? CommonService.mapKeys(mapFn)(value[key]) : value[key]
60 case _.isArray(value):
61 return value.map(CommonService.mapKeys(mapFn));
67 static defaultResponse<R>(promise: AxiosPromise<R>, actions: ApiActions, mapKeys = true): Promise<R> {
69 actions.progressFn(reqId, true);
72 actions.progressFn(reqId, false);
75 .then((response: { data: any }) => {
76 return mapKeys ? CommonService.mapResponseKeys(response) : response.data;
78 .catch(({ response }) => {
79 actions.progressFn(reqId, false);
80 const errors = CommonService.mapResponseKeys(response) as Errors;
81 actions.errorFn(reqId, errors);
86 create(data?: Partial<T>) {
87 return CommonService.defaultResponse(
89 .post<T>(this.resourceType, data && CommonService.mapKeys(_.snakeCase)(data)),
94 delete(uuid: string): Promise<T> {
95 return CommonService.defaultResponse(
97 .delete(this.resourceType + '/' + uuid),
103 return CommonService.defaultResponse(
105 .get<T>(this.resourceType + '/' + uuid),
110 list(args: ListArguments = {}): Promise<ListResults<T>> {
111 const { filters, order, ...other } = args;
114 filters: filters ? `[${filters}]` : undefined,
115 order: order ? order : undefined
118 if (QueryString.stringify(params).length <= 1500) {
119 return CommonService.defaultResponse(
120 this.serverApi.get(this.resourceType, { params }),
124 // Using the POST special case to avoid URI length 414 errors.
125 const formData = new FormData();
126 formData.append("_method", "GET");
127 Object.keys(params).map(key => {
128 if (params[key] !== undefined) {
129 formData.append(key, params[key]);
132 return CommonService.defaultResponse(
133 this.serverApi.post(this.resourceType, formData, {
143 update(uuid: string, data: Partial<T>) {
144 return CommonService.defaultResponse(
146 .put<T>(this.resourceType + '/' + uuid, data && CommonService.mapKeys(_.snakeCase)(data)),