import { callOnce } from "#app";
import { serviceStore } from "~/stores/service";
import useService from "~/composables/use-service";
export default defineNuxtRouteMiddleware(async (to, from) => {
// Ensure this code runs only once
await callOnce(async () => {
const service = serviceStore(); // Pinia store
const { setHealthCheck, getHealthCheck } = useService(); // Composable
// Check if health status is already cached in cookies
const cachedHealthStatus = getHealthCheck();
if (cachedHealthStatus !== null) {
// Set the status in the store from the cookie
service.status = cachedHealthStatus === "true";
return; // Skip API call if status is cached
}
try {
// Perform the health check API call
await service.getCheckHealthz();
// Save the status in cookies based on the API response
await setHealthCheck(service.status);
} catch (error) {
console.error("API Health Check Failed:", error);
// Mark the API as unhealthy and save in cookies
await setHealthCheck(false);
// Optionally throw an error to block the route if necessary
throw createError({
statusCode: 500,
statusMessage: "API is currently unavailable.",
});
}
});
});
import { callOnce } from "#app";
import { serviceStore } from "~/stores/service";
import useService from "~/composables/use-service";
export default defineNuxtRouteMiddleware(async (to, from) => {
// Ensure this code runs only once
await callOnce(async () => {
const service = serviceStore(); // Pinia store
const { setHealthCheck, getHealthCheck } = useService(); // Composable
// Check if health status is already cached in cookies
const cachedHealthStatus = getHealthCheck();
if (cachedHealthStatus !== null) {
// Set the status in the store from the cookie
service.status = cachedHealthStatus === "true";
return; // Skip API call if status is cached
}
try {
// Perform the health check API call
await service.getCheckHealthz();
// Save the status in cookies based on the API response
await setHealthCheck(service.status);
} catch (error) {
console.error("API Health Check Failed:", error);
// Mark the API as unhealthy and save in cookies
await setHealthCheck(false);
// Optionally throw an error to block the route if necessary
throw createError({
statusCode: 500,
statusMessage: "API is currently unavailable.",
});
}
});
});