All files / apps/web/src/utils trpc.ts

100% Statements 13/13
100% Branches 0/0
100% Functions 5/5
100% Lines 13/13

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65                            332x       1669x 1669x 1669x 1669x                   332x     46x 46x                     332x     1669x     46x     332x     1715x            
import { createIsomorphicFn } from "@tanstack/react-start";
import { createTRPCClient } from "@trpc/client";
import type { AnyRouter } from "@trpc/server/unstable-core-do-not-import";
import { createTRPCOptionsProxy } from "@trpc/tanstack-react-query";
import { fromEntries } from "remeda";
 
import { DEFAULT_TRPC_ENDPOINT } from "~app/contexts/links-context";
import type { AppRouter } from "~app/trpc";
import { getLinks } from "~app/utils/trpc";
import type { GetLinksOptions } from "~app/utils/trpc";
import type { RouterContext } from "~web/pages/__root";
import { captureSentryError } from "~web/utils/sentry";
import { getServerHostUrl } from "~web/utils/url";
 
const getServerLinksParams = (
	request: Request,
	source: GetLinksOptions["source"],
) => {
	const url = new URL(request.url);
	url.host = new URL(getServerHostUrl(request.url)).host;
	url.pathname = DEFAULT_TRPC_ENDPOINT;
	return {
		url: url.toString(),
		debug: Boolean(url.searchParams.get("debug")),
		headers: fromEntries([...request.headers.entries()]),
		source,
		captureError: captureSentryError,
	};
};
 
/* c8 ignore start */
const getClientLinksParams = (
	source: GetLinksOptions["source"],
): GetLinksOptions => {
	const url = new URL(window.location.href);
	return {
		url: DEFAULT_TRPC_ENDPOINT,
		debug: Boolean(url.searchParams.get("debug")),
		headers: {},
		source,
		keepError: Boolean(import.meta.env.VITEST),
		captureError: captureSentryError,
	};
};
/* c8 ignore stop */
 
const getIsomorphicLinkParams = createIsomorphicFn()
	.server((request: Request | null): GetLinksOptions =>
		// oxlint-disable-next-line typescript/no-non-null-assertion
		getServerLinksParams(request!, "ssr-loader"),
	)
	/* c8 ignore start */
	.client((): GetLinksOptions => getClientLinksParams("csr-loader"));
/* c8 ignore stop */
 
export const getLoaderTrpcClient = <R extends AnyRouter = AppRouter>(
	context: Pick<RouterContext, "queryClient" | "request">,
) =>
	createTRPCOptionsProxy<R>({
		client: createTRPCClient<R>({
			links: getLinks(getIsomorphicLinkParams(context.request)),
		}),
		queryClient: context.queryClient,
	});