Openstatus
www.openstatus.dev
1import type { HTTPBatchLinkOptions, HTTPHeaders, TRPCLink } from "@trpc/client";
2import { httpBatchLink } from "@trpc/client";
3
4import type { AppRouter } from "@openstatus/api";
5import superjson from "superjson";
6
7const getBaseUrl = () => {
8 if (typeof window !== "undefined") return "";
9 // Note: dashboard has its own tRPC API routes
10 if (process.env.VERCEL_URL) return "https://app.openstatus.dev"; // Vercel
11 return "http://localhost:3000"; // Local dev and Docker (internal calls)
12};
13
14const lambdas = ["stripeRouter", "emailRouter", "apiKeyRouter"];
15
16export const endingLink = (opts?: {
17 fetch?: typeof fetch;
18 headers?: HTTPHeaders | (() => HTTPHeaders | Promise<HTTPHeaders>);
19}) =>
20 ((runtime) => {
21 const sharedOpts = {
22 headers: opts?.headers,
23 fetch: opts?.fetch,
24 transformer: superjson,
25 // biome-ignore lint/suspicious/noExplicitAny: FIXME: remove any
26 } satisfies Partial<HTTPBatchLinkOptions<any>>;
27
28 const edgeLink = httpBatchLink({
29 ...sharedOpts,
30 url: `${getBaseUrl()}/api/trpc/edge`,
31 })(runtime);
32 const lambdaLink = httpBatchLink({
33 ...sharedOpts,
34 url: `${getBaseUrl()}/api/trpc/lambda`,
35 })(runtime);
36
37 return (ctx) => {
38 const path = ctx.op.path.split(".") as [string, ...string[]];
39 const endpoint = lambdas.includes(path[0]) ? "lambda" : "edge";
40
41 const newCtx = {
42 ...ctx,
43 op: { ...ctx.op, path: path.join(".") },
44 };
45 return endpoint === "edge" ? edgeLink(newCtx) : lambdaLink(newCtx);
46 };
47 }) satisfies TRPCLink<AppRouter>;