import { TRPCClientError } from '@trpc/client';
import { httpBatchLink, createTRPCProxyClient } from '@trpc/client';
import type { AppRouter } from '@poseidon/proto-onboard-server/trpc';
import { getServerUrl } from './utils';
import { redirect } from 'next/navigation';
import { getSession } from './auth';
export function isTRPCClientError(
cause: unknown,
): cause is TRPCClientError<AppRouter> {
return cause instanceof TRPCClientError;
}
export const trpc = createTRPCProxyClient<AppRouter>({
links: [
httpBatchLink({
url: `${getServerUrl()}/trpc`,
fetch(url, options) {
return fetch(url, {
...options,
credentials: 'include',
});
},
async headers() {
const session = await getSession();
if (session?.user.accessToken) {
return {
Authorization: `Bearer ${session.user.accessToken}`,
};
}
return {};
},
}),
],
});
export const withClient = <T>(fn: (api: typeof trpc) => Promise<T>) => {
return fn(trpc).catch((cause: unknown) => {
if (isTRPCClientError(cause)) {
if (cause.data?.code === 'UNAUTHORIZED') {
redirect('/en/overview/session-expired');
}
}
throw cause;
});
};