2023-03-15 15:20:08 +00:00
|
|
|
import { useQuery, useQueryClient } from "@tanstack/react-query";
|
|
|
|
const fetchApi = (subPath) => async () =>
|
|
|
|
fetch(`/api${subPath}`).then((res) => res.json());
|
|
|
|
|
|
|
|
const fetchApiPost = (subPath, json) => async () =>
|
|
|
|
fetch(`/api${subPath}`, {
|
|
|
|
method: "POST",
|
|
|
|
headers: {
|
|
|
|
"Content-Type": "application/json",
|
|
|
|
},
|
|
|
|
body: JSON.stringify(json),
|
|
|
|
}).then((res) => res.json());
|
|
|
|
|
|
|
|
export const useServerStatus = (server) =>
|
|
|
|
useQuery(
|
|
|
|
[`server-status-${server}`],
|
2023-10-09 13:42:11 -06:00
|
|
|
fetchApiPost("/server/status", { name: server }),
|
2023-03-15 15:20:08 +00:00
|
|
|
);
|
|
|
|
export const useServerMetrics = (server) =>
|
|
|
|
useQuery(
|
|
|
|
[`server-metrics-${server}`],
|
|
|
|
fetchApiPost("/server/metrics", { name: server }),
|
2023-10-09 13:42:11 -06:00
|
|
|
{ refetchInterval: 10000 },
|
2023-03-15 15:20:08 +00:00
|
|
|
);
|
|
|
|
export const useStartServer = (server) =>
|
|
|
|
postJsonApi("/server/start", { name: server }, "server-instances");
|
|
|
|
export const useStopServer = (server) =>
|
|
|
|
postJsonApi("/server/stop", { name: server }, "server-instances");
|
|
|
|
export const useDeleteServer = (server) =>
|
|
|
|
postJsonApi("/server/delete", { name: server }, "server-instances", "DELETE");
|
|
|
|
export const useCreateServer = (spec) =>
|
|
|
|
postJsonApi("/server/create", spec, "server-list");
|
|
|
|
export const useServerList = () =>
|
|
|
|
useQuery(["server-list"], fetchApi("/server/list"));
|
|
|
|
export const useServerInstances = () =>
|
|
|
|
useQuery(["server-instances"], fetchApi("/server/instances"), {
|
|
|
|
refetchInterval: 5000,
|
|
|
|
});
|
|
|
|
export const useSystemAvailable = () =>
|
|
|
|
useQuery(["system-available"], fetchApi("/system/available"));
|
|
|
|
export const useVersionList = () =>
|
|
|
|
useQuery(["minecraft-versions"], () =>
|
|
|
|
fetch("https://piston-meta.mojang.com/mc/game/version_manifest.json").then(
|
2023-10-09 13:42:11 -06:00
|
|
|
(r) => r.json(),
|
|
|
|
),
|
2023-03-15 15:20:08 +00:00
|
|
|
);
|
|
|
|
|
|
|
|
const postJsonApi = (subPath, body, invalidate, method = "POST") => {
|
|
|
|
const qc = useQueryClient();
|
|
|
|
return async () => {
|
|
|
|
const res = await fetch(`/api${subPath}`, {
|
|
|
|
method,
|
|
|
|
headers: {
|
|
|
|
"Content-Type": "application/json",
|
|
|
|
},
|
|
|
|
body: JSON.stringify(body),
|
|
|
|
});
|
|
|
|
qc.invalidateQueries([invalidate]);
|
|
|
|
};
|
|
|
|
};
|