Refactor api.js: simplify error handling, remove unused functions, and rename routes to endpoints

master^2
Tudor Stanciu 2024-11-16 02:12:21 +02:00
parent 04e80a0ac0
commit ad27fa477d
1 changed files with 2 additions and 51 deletions

View File

@ -1,5 +1,3 @@
import * as axios from "../utils/axios";
import { toast } from "react-toastify";
import env from "../utils/env";
const apiHost = env.REACT_APP_NETWORK_RESURRECTOR_API_URL;
@ -9,7 +7,7 @@ const systemRoute = `${apiHost}/system`;
const powerActionsRoute = `${apiHost}/resurrector`;
const securityRoute = `${apiHost}/security`;
const routes = {
const endpoints = {
network: {
machines: `${networkRoute}/machines`,
machine: {
@ -29,51 +27,4 @@ const routes = {
}
};
const handleError = err => {
let message;
switch (err?.status) {
case 500:
message = err.title;
break;
case 404:
message = err.message;
break;
default:
message = err.title;
}
toast.error(message);
};
const defaultOptions = {
onCompleted: () => null,
onError: handleError
};
const call = async (request, options = defaultOptions) => {
const internalOptions = { ...defaultOptions, ...options };
const { onCompleted, onError } = internalOptions;
try {
const result = await request();
onCompleted(result);
} catch (error) {
onError(error);
}
};
const get = (route, options) => {
const promise = call(() => axios.get(route), options);
return promise;
};
const post = (route, data, options) => {
const promise = call(() => axios.post(route, data), options);
return promise;
};
const endpoints = routes;
export { routes, get, post, endpoints };
export { endpoints };