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";
9 import { Resource } from "../../models/resource";
11 export interface ListArguments {
14 filters?: FilterBuilder;
21 export interface ListResults<T> {
26 itemsAvailable: number;
29 export default class CommonResourceService<T extends Resource> {
31 static mapResponseKeys = (response: any): Promise<any> =>
32 CommonResourceService.mapKeys(_.camelCase)(response.data)
34 static mapKeys = (mapFn: (key: string) => string) =>
35 (value: any): any => {
37 case _.isPlainObject(value):
40 .map(key => [key, mapFn(key)])
41 .reduce((newValue, [key, newKey]) => ({
43 [newKey]: CommonResourceService.mapKeys(mapFn)(value[key])
45 case _.isArray(value):
46 return value.map(CommonResourceService.mapKeys(mapFn));
52 protected serverApi: AxiosInstance;
53 protected resourceType: string;
55 constructor(serverApi: AxiosInstance, resourceType: string) {
56 this.serverApi = serverApi;
57 this.resourceType = '/' + resourceType + '/';
60 create(data: Partial<T>) {
62 .post<T>(this.resourceType, CommonResourceService.mapKeys(_.snakeCase)(data))
63 .then(CommonResourceService.mapResponseKeys);
66 delete(uuid: string): Promise<T> {
68 .delete(this.resourceType + uuid)
69 .then(CommonResourceService.mapResponseKeys);
74 .get<T>(this.resourceType + uuid)
75 .then(CommonResourceService.mapResponseKeys);
78 list(args: ListArguments = {}): Promise<ListResults<T>> {
79 const { filters, order, ...other } = args;
82 filters: filters ? filters.serialize() : undefined,
83 order: order ? order.getOrder() : undefined
86 .get(this.resourceType, {
87 params: CommonResourceService.mapKeys(_.snakeCase)(params)
89 .then(CommonResourceService.mapResponseKeys);
92 update(uuid: string) {
93 throw new Error("Not implemented");