mw
mw11mo ago

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;
}
4 Replies
wleistra
wleistra11mo ago
This is how we are doing it for our product and it seems to work well
mw
mw11mo ago
Thanks @wleistra
Alex / KATT 🐱
Alex / KATT 🐱11mo ago
Lgtm
mw
mw11mo ago
Thanks @alexkatt