lattmamb/aether-rides
0
1import { QueryClient, QueryFunction } from "@tanstack/react-query";2 3async function throwIfResNotOk(res: Response) {4 if (!res.ok) {5 const text = (await res.text()) || res.statusText;6 throw new Error(`${res.status}: ${text}`);7 }8}9 10export async function apiRequest(11 method: string,12 url: string,13 data?: unknown | undefined,14): Promise<Response> {15 const res = await fetch(url, {16 method,17 headers: data ? { "Content-Type": "application/json" } : {},18 body: data ? JSON.stringify(data) : undefined,19 credentials: "include",20 });21 22 await throwIfResNotOk(res);23 return res;24}25 26type UnauthorizedBehavior = "returnNull" | "throw";27export const getQueryFn: <T>(options: {28 on401: UnauthorizedBehavior;29}) => QueryFunction<T> =30 ({ on401: unauthorizedBehavior }) =>31 async ({ queryKey }) => {32 const res = await fetch(queryKey[0] as string, {33 credentials: "include",34 });35 36 if (unauthorizedBehavior === "returnNull" && res.status === 401) {37 return null;38 }39 40 await throwIfResNotOk(res);41 return await res.json();42 };43 44export const queryClient = new QueryClient({45 defaultOptions: {46 queries: {47 queryFn: getQueryFn({ on401: "throw" }),48 refetchInterval: false,49 refetchOnWindowFocus: false,50 staleTime: Infinity,51 retry: false,52 },53 mutations: {54 retry: false,55 },56 },57});58 