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 if (process.env.VERCEL_URL) return `https://${process.env.VERCEL_URL}`; // Vercel
10 return "http://localhost:3000"; // Local dev
11};
12
13const lambdas = ["stripeRouter", "emailRouter"];
14
15export const endingLink = (opts?: {
16 headers?: HTTPHeaders | (() => HTTPHeaders | Promise<HTTPHeaders>);
17}) =>
18 ((runtime) => {
19 const sharedOpts = {
20 headers: opts?.headers, // REMINDER: fails when trying to `getTotalActiveMonitors()`
21 transformer: superjson,
22 // biome-ignore lint/suspicious/noExplicitAny: FIXME: remove any
23 } satisfies Partial<HTTPBatchLinkOptions<any>>;
24
25 const edgeLink = httpBatchLink({
26 ...sharedOpts,
27 url: `${getBaseUrl()}/api/trpc/edge`,
28 })(runtime);
29 const lambdaLink = httpBatchLink({
30 ...sharedOpts,
31 url: `${getBaseUrl()}/api/trpc/lambda`,
32 })(runtime);
33
34 return (ctx) => {
35 const path = ctx.op.path.split(".") as [string, ...string[]];
36 const endpoint = lambdas.includes(path[0]) ? "lambda" : "edge";
37
38 const newCtx = {
39 ...ctx,
40 op: { ...ctx.op, path: path.join(".") },
41 };
42 return endpoint === "edge" ? edgeLink(newCtx) : lambdaLink(newCtx);
43 };
44 }) satisfies TRPCLink<AppRouter>;