// SPDX-License-Identifier: AGPL-3.0
import * as _ from "lodash";
-import FilterBuilder from "./filter-builder";
-import OrderBuilder from "./order-builder";
-import { AxiosInstance } from "axios";
+import { FilterBuilder } from "./filter-builder";
+import { OrderBuilder } from "./order-builder";
+import { AxiosInstance, AxiosPromise } from "axios";
import { Resource } from "../../models/resource";
export interface ListArguments {
itemsAvailable: number;
}
-export default class CommonResourceService<T extends Resource> {
+export interface Errors {
+ errors: string[];
+ errorToken: string;
+}
+
+export class CommonResourceService<T extends Resource> {
static mapResponseKeys = (response: any): Promise<any> =>
CommonResourceService.mapKeys(_.camelCase)(response.data)
}
}
+ static defaultResponse<R>(promise: AxiosPromise<R>): Promise<R> {
+ return promise
+ .then(CommonResourceService.mapResponseKeys)
+ .catch(({ response }) => Promise.reject<Errors>(CommonResourceService.mapResponseKeys(response)));
+ }
+
protected serverApi: AxiosInstance;
protected resourceType: string;
}
create(data: Partial<T>) {
- return this.serverApi
- .post<T>(this.resourceType, CommonResourceService.mapKeys(_.snakeCase)(data))
- .then(CommonResourceService.mapResponseKeys);
+ return CommonResourceService.defaultResponse(
+ this.serverApi
+ .post<T>(this.resourceType, CommonResourceService.mapKeys(_.snakeCase)(data)));
}
delete(uuid: string): Promise<T> {
- return this.serverApi
- .delete(this.resourceType + uuid)
- .then(CommonResourceService.mapResponseKeys);
+ return CommonResourceService.defaultResponse(
+ this.serverApi
+ .delete(this.resourceType + uuid));
}
get(uuid: string) {
- return this.serverApi
- .get<T>(this.resourceType + uuid)
- .then(CommonResourceService.mapResponseKeys);
+ return CommonResourceService.defaultResponse(
+ this.serverApi
+ .get<T>(this.resourceType + uuid));
}
list(args: ListArguments = {}): Promise<ListResults<T>> {
filters: filters ? filters.serialize() : undefined,
order: order ? order.getOrder() : undefined
};
- return this.serverApi
- .get(this.resourceType, {
- params: CommonResourceService.mapKeys(_.snakeCase)(params)
- })
- .then(CommonResourceService.mapResponseKeys);
+ return CommonResourceService.defaultResponse(
+ this.serverApi
+ .get(this.resourceType, {
+ params: CommonResourceService.mapKeys(_.snakeCase)(params)
+ }));
}
update(uuid: string) {
throw new Error("Not implemented");
}
-
}