46 lines
1.5 KiB
TypeScript
46 lines
1.5 KiB
TypeScript
import { QueryClient } from "@tanstack/react-query";
|
|
import { ApiRequestError, invalidResponseCode } from "../../shared/api";
|
|
|
|
/** Automatic retries after the first failure of a query. */
|
|
export const maxQueryRetries = 2;
|
|
|
|
/**
|
|
* Retries only failures that a later attempt can fix: no response (status 0)
|
|
* and server errors other than 501. Client errors (4xx), invalid response
|
|
* bodies, and programming errors fail at once so their state shows quickly.
|
|
*/
|
|
export function shouldRetryQuery(failureCount: number, error: unknown): boolean {
|
|
if (failureCount >= maxQueryRetries || !(error instanceof ApiRequestError)) {
|
|
return false;
|
|
}
|
|
if (error.code === invalidResponseCode) {
|
|
return false;
|
|
}
|
|
return error.status === 0 || (error.status >= 500 && error.status !== 501);
|
|
}
|
|
|
|
/**
|
|
* Server cache for the application. Generated Orval hooks supply each query
|
|
* function through the shared same-origin apiRequest client, so there is no
|
|
* default query function here.
|
|
*
|
|
* Window focus does not refetch: cabinets hold forms and long reads where a
|
|
* background refetch would flicker states; screens that need fresh data opt
|
|
* in per query. Mutations never retry automatically because they are not
|
|
* idempotent until the API supports Idempotency-Key.
|
|
*/
|
|
export function createQueryClient(): QueryClient {
|
|
return new QueryClient({
|
|
defaultOptions: {
|
|
queries: {
|
|
retry: shouldRetryQuery,
|
|
staleTime: 30_000,
|
|
refetchOnWindowFocus: false,
|
|
},
|
|
mutations: {
|
|
retry: false,
|
|
},
|
|
},
|
|
});
|
|
}
|