| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263 |
- import { trpc } from "@/lib/trpc";
- import { UNAUTHED_ERR_MSG } from '@shared/const';
- import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
- import { httpBatchLink, TRPCClientError } from "@trpc/client";
- import { createRoot } from "react-dom/client";
- import superjson from "superjson";
- import App from "./App";
- import { getLoginUrl } from "./const";
- import "./index.css";
- const queryClient = new QueryClient();
- const redirectToLoginIfUnauthorized = (error: unknown) => {
- if (!(error instanceof TRPCClientError)) return;
- if (typeof window === "undefined") return;
- const isUnauthorized = error.message === UNAUTHED_ERR_MSG;
- if (!isUnauthorized) return;
- // Redirect to our custom login page instead of OAuth
- const currentPath = window.location.pathname;
- window.location.href = `${import.meta.env.BASE_URL}login?returnTo=${encodeURIComponent(currentPath)}`;
- };
- queryClient.getQueryCache().subscribe(event => {
- if (event.type === "updated" && event.action.type === "error") {
- const error = event.query.state.error;
- redirectToLoginIfUnauthorized(error);
- console.error("[API Query Error]", error);
- }
- });
- queryClient.getMutationCache().subscribe(event => {
- if (event.type === "updated" && event.action.type === "error") {
- const error = event.mutation.state.error;
- redirectToLoginIfUnauthorized(error);
- console.error("[API Mutation Error]", error);
- }
- });
- const trpcClient = trpc.createClient({
- links: [
- httpBatchLink({
- url: `${import.meta.env.BASE_URL}api/trpc`,
- transformer: superjson,
- fetch(input, init) {
- return globalThis.fetch(input, {
- ...(init ?? {}),
- credentials: "include",
- });
- },
- }),
- ],
- });
- createRoot(document.getElementById("root")!).render(
- <trpc.Provider client={trpcClient} queryClient={queryClient}>
- <QueryClientProvider client={queryClient}>
- <App />
- </QueryClientProvider>
- </trpc.Provider>
- );
|