1 // Copyright (C) The Arvados Authors. All rights reserved.
3 // SPDX-License-Identifier: AGPL-3.0
5 import * as _ from "lodash";
6 import { FilterBuilder } from "./filter-builder";
7 import { OrderBuilder } from "./order-builder";
8 import { AxiosInstance, AxiosPromise } from "axios";
9 import { Resource } from "../../models/resource";
11 export interface ListArguments {
14 filters?: FilterBuilder;
21 export interface ListResults<T> {
26 itemsAvailable: number;
29 export interface Errors {
34 export class CommonResourceService<T extends Resource> {
36 static mapResponseKeys = (response: any): Promise<any> =>
37 CommonResourceService.mapKeys(_.camelCase)(response.data)
39 static mapKeys = (mapFn: (key: string) => string) =>
40 (value: any): any => {
42 case _.isPlainObject(value):
45 .map(key => [key, mapFn(key)])
46 .reduce((newValue, [key, newKey]) => ({
48 [newKey]: CommonResourceService.mapKeys(mapFn)(value[key])
50 case _.isArray(value):
51 return value.map(CommonResourceService.mapKeys(mapFn));
57 static defaultResponse<R>(promise: AxiosPromise<R>): Promise<R> {
59 .then(CommonResourceService.mapResponseKeys)
60 .catch(({ response }) => Promise.reject<Errors>(CommonResourceService.mapResponseKeys(response)));
63 protected serverApi: AxiosInstance;
64 protected resourceType: string;
66 constructor(serverApi: AxiosInstance, resourceType: string) {
67 this.serverApi = serverApi;
68 this.resourceType = '/' + resourceType + '/';
71 create(data?: Partial<T> | any) {
72 return CommonResourceService.defaultResponse(
74 .post<T>(this.resourceType, data && CommonResourceService.mapKeys(_.snakeCase)(data)));
77 delete(uuid: string): Promise<T> {
78 return CommonResourceService.defaultResponse(
80 .delete(this.resourceType + uuid));
84 return CommonResourceService.defaultResponse(
86 .get<T>(this.resourceType + uuid));
89 list(args: ListArguments = {}): Promise<ListResults<T>> {
90 const { filters, order, ...other } = args;
93 filters: filters ? filters.serialize() : undefined,
94 order: order ? order.getOrder() : undefined
96 return CommonResourceService.defaultResponse(
98 .get(this.resourceType, {
99 params: CommonResourceService.mapKeys(_.snakeCase)(params)
103 update(uuid: string, data: any) {
104 return CommonResourceService.defaultResponse(
106 .put<T>(this.resourceType + uuid, data));