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 } from "axios";
10 export interface Resource {
14 modifiedByClientUuid: string;
15 modifiedByUserUuid: string;
22 export interface ListArguments {
25 filters?: FilterBuilder;
32 export interface ListResults<T> {
37 itemsAvailable: number;
40 export default class CommonResourceService<T extends Resource> {
42 static mapResponseKeys = (response: any): Promise<any> =>
43 CommonResourceService.mapKeys(_.camelCase)(response.data)
45 static mapKeys = (mapFn: (key: string) => string) =>
46 (value: any): any => {
48 case _.isPlainObject(value):
51 .map(key => [key, mapFn(key)])
52 .reduce((newValue, [key, newKey]) => ({
54 [newKey]: CommonResourceService.mapKeys(mapFn)(value[key])
56 case _.isArray(value):
57 return value.map(CommonResourceService.mapKeys(mapFn));
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>) {
73 .post<T>(this.resourceType, CommonResourceService.mapKeys(_.snakeCase)(data))
74 .then(CommonResourceService.mapResponseKeys);
77 delete(uuid: string): Promise<T> {
79 .delete(this.resourceType + uuid)
80 .then(CommonResourceService.mapResponseKeys);
85 .get<T>(this.resourceType + uuid)
86 .then(CommonResourceService.mapResponseKeys);
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
97 .get(this.resourceType, {
98 params: CommonResourceService.mapKeys(_.snakeCase)(params)
100 .then(CommonResourceService.mapResponseKeys);
103 update(uuid: string) {
104 throw new Error("Not implemented");