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 { Resource } from "~/models/resource";
9 export interface ListArguments {
19 export interface ListResults<T> {
24 itemsAvailable: number;
27 export interface Errors {
32 export enum CommonResourceServiceError {
33 UNIQUE_VIOLATION = 'UniqueViolation',
38 export class CommonResourceService<T extends Resource> {
40 static mapResponseKeys = (response: any): Promise<any> =>
41 CommonResourceService.mapKeys(_.camelCase)(response.data)
43 static mapKeys = (mapFn: (key: string) => string) =>
44 (value: any): any => {
46 case _.isPlainObject(value):
49 .map(key => [key, mapFn(key)])
50 .reduce((newValue, [key, newKey]) => ({
52 [newKey]: CommonResourceService.mapKeys(mapFn)(value[key])
54 case _.isArray(value):
55 return value.map(CommonResourceService.mapKeys(mapFn));
61 static defaultResponse<R>(promise: AxiosPromise<R>): Promise<R> {
63 .then(CommonResourceService.mapResponseKeys)
64 .catch(({ response }) => Promise.reject<Errors>(CommonResourceService.mapResponseKeys(response)));
67 protected serverApi: AxiosInstance;
68 protected resourceType: string;
70 constructor(serverApi: AxiosInstance, resourceType: string) {
71 this.serverApi = serverApi;
72 this.resourceType = '/' + resourceType + '/';
75 create(data?: Partial<T> | any) {
76 return CommonResourceService.defaultResponse(
78 .post<T>(this.resourceType, data && CommonResourceService.mapKeys(_.snakeCase)(data)));
81 delete(uuid: string): Promise<T> {
82 return CommonResourceService.defaultResponse(
84 .delete(this.resourceType + uuid));
88 return CommonResourceService.defaultResponse(
90 .get<T>(this.resourceType + uuid));
93 list(args: ListArguments = {}): Promise<ListResults<T>> {
94 const { filters, order, ...other } = args;
97 filters: filters ? `[${filters}]` : undefined,
98 order: order ? order : undefined
100 return CommonResourceService.defaultResponse(
102 .get(this.resourceType, {
103 params: CommonResourceService.mapKeys(_.snakeCase)(params)
107 update(uuid: string, data: any) {
108 return CommonResourceService.defaultResponse(
110 .put<T>(this.resourceType + uuid, data));
115 export const getCommonResourceServiceError = (errorResponse: any) => {
116 if ('errors' in errorResponse && 'errorToken' in errorResponse) {
117 const error = errorResponse.errors.join('');
119 case /UniqueViolation/.test(error):
120 return CommonResourceServiceError.UNIQUE_VIOLATION;
122 return CommonResourceServiceError.UNKNOWN;
125 return CommonResourceServiceError.NONE;