mwM
tRPC3y ago
6 replies
mw

I have a websocket + REST project. Should I be using splitLink like this to combine WS and HTTP?

I have a backend project that uses REST for queries/mutations and Websockets for subscriptions.

I just want validation: is this exactly what I should be doing?

Is there some other simpler way that I'm missing?

Thank you for the great project.

import { createTRPCProxyClient, httpLink, createWSClient, wsLink, splitLink } from "@trpc/client";
import type { AppRouter } from "backend/src/trpc/appRouter.trpc";
import { browser } from '$app/environment';

let instance: ReturnType<typeof createTRPCProxyClient<AppRouter>>;

export const getTrpcClient = () => {
  if (!instance) {
    const websocketClient = createWSClient({
      url: "ws://localhost:3001",
    });

    instance = createTRPCProxyClient<AppRouter>({
      links: [
        splitLink({
          condition(op) {
            return op.type === 'subscription'
          },
          true: wsLink({
            client: websocketClient
          }),
          false: httpLink({
            url: "http://localhost:3000/trpc",
          })
        })
      ]
    });
  }

  return instance;
}
Was this page helpful?