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',
34 OWNERSHIP_CYCLE = 'OwnershipCycle',
39 export class CommonResourceService<T extends Resource> {
41 static mapResponseKeys = (response: any): Promise<any> =>
42 CommonResourceService.mapKeys(_.camelCase)(response.data)
44 static mapKeys = (mapFn: (key: string) => string) =>
45 (value: any): any => {
47 case _.isPlainObject(value):
50 .map(key => [key, mapFn(key)])
51 .reduce((newValue, [key, newKey]) => ({
53 [newKey]: CommonResourceService.mapKeys(mapFn)(value[key])
55 case _.isArray(value):
56 return value.map(CommonResourceService.mapKeys(mapFn));
62 static defaultResponse<R>(promise: AxiosPromise<R>): Promise<R> {
64 .then(CommonResourceService.mapResponseKeys)
65 .catch(({ response }) => Promise.reject<Errors>(CommonResourceService.mapResponseKeys(response)));
68 protected serverApi: AxiosInstance;
69 protected resourceType: string;
71 constructor(serverApi: AxiosInstance, resourceType: string) {
72 this.serverApi = serverApi;
73 this.resourceType = '/' + resourceType + '/';
76 create(data?: Partial<T> | any) {
77 return CommonResourceService.defaultResponse(
79 .post<T>(this.resourceType, data && CommonResourceService.mapKeys(_.snakeCase)(data)));
82 delete(uuid: string): Promise<T> {
83 return CommonResourceService.defaultResponse(
85 .delete(this.resourceType + uuid));
89 return CommonResourceService.defaultResponse(
91 .get<T>(this.resourceType + uuid));
94 list(args: ListArguments = {}): Promise<ListResults<T>> {
95 const { filters, order, ...other } = args;
98 filters: filters ? `[${filters}]` : undefined,
99 order: order ? order : undefined
101 return CommonResourceService.defaultResponse(
103 .get(this.resourceType, {
104 params: CommonResourceService.mapKeys(_.snakeCase)(params)
108 update(uuid: string, data: Partial<T>) {
109 return CommonResourceService.defaultResponse(
111 .put<T>(this.resourceType + uuid, data && CommonResourceService.mapKeys(_.snakeCase)(data)));
116 export const getCommonResourceServiceError = (errorResponse: any) => {
117 if ('errors' in errorResponse && 'errorToken' in errorResponse) {
118 const error = errorResponse.errors.join('');
120 case /UniqueViolation/.test(error):
121 return CommonResourceServiceError.UNIQUE_VIOLATION;
122 case /ownership cycle/.test(error):
123 return CommonResourceServiceError.OWNERSHIP_CYCLE;
125 return CommonResourceServiceError.UNKNOWN;
128 return CommonResourceServiceError.NONE;