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 class CommonResourceService<T extends Resource> {
34 static mapResponseKeys = (response: any): Promise<any> =>
35 CommonResourceService.mapKeys(_.camelCase)(response.data)
37 static mapKeys = (mapFn: (key: string) => string) =>
38 (value: any): any => {
40 case _.isPlainObject(value):
43 .map(key => [key, mapFn(key)])
44 .reduce((newValue, [key, newKey]) => ({
46 [newKey]: CommonResourceService.mapKeys(mapFn)(value[key])
48 case _.isArray(value):
49 return value.map(CommonResourceService.mapKeys(mapFn));
55 static defaultResponse<R>(promise: AxiosPromise<R>): Promise<R> {
57 .then(CommonResourceService.mapResponseKeys)
58 .catch(({ response }) => Promise.reject<Errors>(CommonResourceService.mapResponseKeys(response)));
61 protected serverApi: AxiosInstance;
62 protected resourceType: string;
64 constructor(serverApi: AxiosInstance, resourceType: string) {
65 this.serverApi = serverApi;
66 this.resourceType = '/' + resourceType + '/';
69 create(data?: Partial<T> | any) {
70 return CommonResourceService.defaultResponse(
72 .post<T>(this.resourceType, data && CommonResourceService.mapKeys(_.snakeCase)(data)));
75 delete(uuid: string): Promise<T> {
76 return CommonResourceService.defaultResponse(
78 .delete(this.resourceType + uuid));
82 return CommonResourceService.defaultResponse(
84 .get<T>(this.resourceType + uuid));
87 list(args: ListArguments = {}): Promise<ListResults<T>> {
88 const { filters, order, ...other } = args;
91 filters: filters ? `[${filters}]` : undefined,
92 order: order ? order : undefined
94 return CommonResourceService.defaultResponse(
96 .get(this.resourceType, {
97 params: CommonResourceService.mapKeys(_.snakeCase)(params)
101 update(uuid: string, data: any) {
102 return CommonResourceService.defaultResponse(
104 .put<T>(this.resourceType + uuid, data));