tRPCttRPC
Powered by
mwM
tRPC•3y 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;
}
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;
}
tRPCJoin
Move Fast & Break Nothing. End-to-end typesafe APIs made easy.
5,015Members
Resources
Recent Announcements

Similar Threads

Was this page helpful?

Similar Threads

Why do people use SplitLink? (http + websocket)
Ben-xDBBen-xD / ❓-help
3y ago
Is there a way to define the Websocket protocol when using wsLink()
molochMmoloch / ❓-help
3y ago
useQueries passing ctx data to splitLink not working
vildantursicVvildantursic / ❓-help
3y ago
Error "Subscriptions should use wsLink"
jaacsenJjaacsen / ❓-help
2y ago