added globalEndpointCache to prevent re-fetching

This commit is contained in:
Dario Ghunney Ware
2025-10-30 11:21:41 +00:00
committed by DarioGii
parent 19f40d053a
commit b4f9ed031e

View File

@@ -1,6 +1,10 @@
import { useState, useEffect } from 'react';
import { useRequestHeaders } from '@app/hooks/useRequestHeaders';
// Track globally fetched endpoint sets to prevent duplicate fetches across components
const globalFetchedSets = new Set<string>();
const globalEndpointCache: Record<string, boolean> = {};
// Helper to get JWT from localStorage for Authorization header
function getAuthHeaders(): HeadersInit {
const token = localStorage.getItem('stirling_jwt');
@@ -79,12 +83,19 @@ export function useMultipleEndpointsEnabled(endpoints: string[]): {
const [lastFetchedEndpoints, setLastFetchedEndpoints] = useState<string>('');
const _headers = useRequestHeaders();
const fetchAllEndpointStatuses = async () => {
const endpointsKey = endpoints.join(',');
const fetchAllEndpointStatuses = async (force = false) => {
const endpointsKey = [...endpoints].sort().join(',');
// Skip if we already fetched these exact endpoints
if (lastFetchedEndpoints === endpointsKey && Object.keys(endpointStatus).length > 0) {
console.debug('[useEndpointConfig] Already fetched these endpoints, skipping');
// Skip if we already fetched these exact endpoints globally
if (!force && globalFetchedSets.has(endpointsKey)) {
console.debug('[useEndpointConfig] Already fetched these endpoints globally, using cache');
const cachedStatus = endpoints.reduce((acc, endpoint) => {
if (endpoint in globalEndpointCache) {
acc[endpoint] = globalEndpointCache[endpoint];
}
return acc;
}, {} as Record<string, boolean>);
setEndpointStatus(cachedStatus);
setLoading(false);
return;
}
@@ -111,8 +122,22 @@ export function useMultipleEndpointsEnabled(endpoints: string[]): {
setLoading(true);
setError(null);
// Use batch API for efficiency
const endpointsParam = endpoints.join(',');
// Check which endpoints we haven't fetched yet
const newEndpoints = endpoints.filter(ep => !(ep in globalEndpointCache));
if (newEndpoints.length === 0) {
console.debug('[useEndpointConfig] All endpoints already in global cache');
const cachedStatus = endpoints.reduce((acc, endpoint) => {
acc[endpoint] = globalEndpointCache[endpoint];
return acc;
}, {} as Record<string, boolean>);
setEndpointStatus(cachedStatus);
globalFetchedSets.add(endpointsKey);
setLoading(false);
return;
}
// Use batch API for efficiency - only fetch new endpoints
const endpointsParam = newEndpoints.join(',');
const response = await fetch(`/api/v1/config/endpoints-enabled?endpoints=${encodeURIComponent(endpointsParam)}`, {
headers: getAuthHeaders(),
@@ -124,6 +149,7 @@ export function useMultipleEndpointsEnabled(endpoints: string[]): {
console.warn('[useEndpointConfig] 401 error - using optimistic fallback');
const optimisticStatus = endpoints.reduce((acc, endpoint) => {
acc[endpoint] = true;
globalEndpointCache[endpoint] = true; // Cache the optimistic value
return acc;
}, {} as Record<string, boolean>);
setEndpointStatus(optimisticStatus);
@@ -134,7 +160,18 @@ export function useMultipleEndpointsEnabled(endpoints: string[]): {
}
const statusMap: Record<string, boolean> = await response.json();
setEndpointStatus(statusMap);
// Update global cache with new results
Object.assign(globalEndpointCache, statusMap);
// Get all requested endpoints from cache (including previously cached ones)
const fullStatus = endpoints.reduce((acc, endpoint) => {
acc[endpoint] = globalEndpointCache[endpoint] ?? true; // Default to true if not in cache
return acc;
}, {} as Record<string, boolean>);
setEndpointStatus(fullStatus);
globalFetchedSets.add(endpointsKey);
setLastFetchedEndpoints(endpointsKey);
} catch (err) {
const errorMessage = err instanceof Error ? err.message : 'Unknown error occurred';
@@ -159,10 +196,12 @@ export function useMultipleEndpointsEnabled(endpoints: string[]): {
// Listen for JWT availability (triggered on login/signup)
useEffect(() => {
const handleJwtAvailable = () => {
console.debug('[useEndpointConfig] JWT available event - refetching endpoints');
// Reset to allow refetch with JWT
console.debug('[useEndpointConfig] JWT available event - clearing cache for refetch with auth');
// Clear the global cache to allow refetch with JWT
globalFetchedSets.clear();
Object.keys(globalEndpointCache).forEach(key => delete globalEndpointCache[key]);
setLastFetchedEndpoints('');
fetchAllEndpointStatuses();
fetchAllEndpointStatuses(true);
};
window.addEventListener('jwt-available', handleJwtAvailable);
@@ -173,6 +212,6 @@ export function useMultipleEndpointsEnabled(endpoints: string[]): {
endpointStatus,
loading,
error,
refetch: fetchAllEndpointStatuses,
refetch: () => fetchAllEndpointStatuses(true),
};
}