Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
52 changes: 35 additions & 17 deletions src/frontend/src/api/apiUtils.ts
Original file line number Diff line number Diff line change
@@ -1,25 +1,39 @@
import { queryClient } from './queryClient';

/**
* Handle unauthorized errors by updating the auth state in the query cache
* This will trigger the AuthModal to appear
*/
export function handleUnauthorized() {
// Set auth state to false to trigger the AuthModal
queryClient.setQueryData(['auth'], false);
}

// Common error handling for API responses
export async function handleResponse(response: Response) {
if (!response.ok) {
if (response.status === 401) {
throw new Error('Unauthorized');
}

const errorText = await response.text();
throw new Error(errorText || `API error: ${response.status}`);
if (!response.ok) {
if (response.status === 401) {
// Update auth state when 401 is encountered
handleUnauthorized();
throw new Error('Unauthorized');
}

// For endpoints that return no content
if (response.status === 204) {
return null;
}

// For endpoints that return JSON
return response.json();
const errorText = await response.text();
throw new Error(errorText || `API error: ${response.status}`);
}

// Base fetch function with error handling
export async function fetchApi(url: string, options?: RequestInit) {
// For endpoints that return no content
if (response.status === 204) {
return null;
}

// For endpoints that return JSON
return response.json();
}

// Base fetch function with error handling
export async function fetchApi(url: string, options?: RequestInit) {
try {
const response = await fetch(url, {
...options,
credentials: 'include',
Expand All @@ -30,4 +44,8 @@ export async function handleResponse(response: Response) {
});

return handleResponse(response);
}
} catch (error) {
// Re-throw the error after handling it
throw error;
}
}
1 change: 1 addition & 0 deletions src/frontend/src/api/hooks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,7 @@ export const api = {
// Map backend 'state' property to frontend 'status'
return { ...result, status: result.state };
} catch (error) {
// Let the error propagate to be handled by the global error handler
throw error;
}
},
Expand Down
2 changes: 1 addition & 1 deletion src/frontend/src/api/queryClient.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ export const queryClient = new QueryClient({
retry: 1,
refetchOnWindowFocus: true,
staleTime: 30000, // 30 seconds
cacheTime: 1000 * 60 * 5, // 5 minutes
gcTime: 1000 * 60 * 5, // 5 minutes (formerly cacheTime)
refetchOnMount: true,
},
},
Expand Down