network-resurrector/src/api/useApi.js

70 lines
1.6 KiB
JavaScript
Raw Normal View History

2022-01-18 14:08:04 +02:00
import { useToast } from "../hooks";
import { get, post } from "../utils/axios";
const networkRoute = `${process.env.REACT_APP_NETWORK_RESURRECTOR_API_URL}/network`;
const powerActionsRoute = `${process.env.REACT_APP_NETWORK_RESURRECTOR_API_URL}/resurrector`;
const useApi = () => {
const { error } = useToast();
const handleError = err => {
let message;
2022-01-18 14:56:18 +02:00
switch (err?.status) {
2022-01-18 14:08:04 +02:00
case 500:
2022-01-18 14:56:18 +02:00
message = `${err.title} ${err.correlationId}`;
2022-01-18 14:08:04 +02:00
break;
2022-01-18 14:56:18 +02:00
case 404:
2022-01-18 14:08:04 +02:00
message = err.message;
2022-01-18 14:56:18 +02:00
break;
default:
message = `${err.title} ${err.correlationId}`;
2022-01-18 14:08:04 +02:00
}
error(message);
};
const defaultOptions = { onCompleted: () => {}, onError: handleError };
const call = async (request, options) => {
const internalOptions = { ...defaultOptions, ...options };
const { onCompleted, onError } = internalOptions;
try {
const result = await request();
onCompleted(result);
} catch (error) {
onError(error);
}
};
const readMachines = (options = defaultOptions) => {
const machinesPromise = call(
() => get(`${networkRoute}/machines`),
options
);
return machinesPromise;
};
const wakeMachine = (machineId, options = defaultOptions) => {
const promise = call(
() => post(`${powerActionsRoute}/wake`, { machineId }),
options
);
return promise;
};
const pingMachine = (machineId, options = defaultOptions) => {
const promise = call(
() => post(`${powerActionsRoute}/ping`, { machineId }),
options
);
return promise;
};
return { readMachines, wakeMachine, pingMachine };
};
export default useApi;