41 lines
895 B
TypeScript
41 lines
895 B
TypeScript
import { useEffect, useState } from "react";
|
|||
|
|
|
||
|
|
type Status = "idle" | "ok" | "error";
|
||
|
|
|
||
|
|
export function useBackendHealth() {
|
||
|
|
const [status, setStatus] = useState<Status>(() => {
|
||
|
|
if (!process.env.NEXT_PUBLIC_BACKEND_URL) {
|
||
|
|
return "error";
|
||
|
|
}
|
||
|
|
return "idle";
|
||
|
|
});
|
||
|
|
|
||
|
|
useEffect(() => {
|
||
|
|
let destroyed = false;
|
||
|
|
const url = process.env.NEXT_PUBLIC_BACKEND_URL;
|
||
|
|
if (!url) {
|
||
|
|
return;
|
||
|
|
}
|
||
|
|
const controller = new AbortController();
|
||
|
|
const check = async () => {
|
||
|
|
try {
|
||
|
|
const response = await fetch(`${url}/health`, { signal: controller.signal });
|
||
|
|
if (!destroyed) {
|
||
|
|
setStatus(response.ok ? "ok" : "error");
|
||
|
|
}
|
||
|
|
} catch {
|
||
|
|
if (!destroyed) {
|
||
|
|
setStatus("error");
|
||
|
|
}
|
||
|
|
}
|
||
|
|
};
|
||
|
|
check();
|
||
|
|
return () => {
|
||
|
|
destroyed = true;
|
||
|
|
controller.abort();
|
||
|
|
};
|
||
|
|
}, []);
|
||
|
|
|
||
|
|
return status;
|
||
|
|
}
|