dylan42432D
tRPC9mo ago
1 reply
dylan42432

Unref() the websocket

Hello everyone,

What I desire is to use a websocket link but not have TRPC hold the process open indefinitely, preventing my Node.js script from finishing (as is default when you have a websocket connection open). If you merely unref() the underlying socket then the process quits before the query/mutation finishes.

The following is my working solution, but I'm wondering if there was a simpler/more elegant solution:

const ensureProcessLives: TRPCLink<AppRouter> = () => {
            return ({ next, op }) => {
                return observable((observer) => {
                    const keepAliveTimeout = setTimeout(() => {}, 2147483647);

                    return next(op).subscribe({
                        next(value) {
                            observer.next(value);
                        },
                        error(err) {
                            observer.error(err);
                            clearTimeout(keepAliveTimeout);
                        },
                        complete() {
                            observer.complete();
                            clearTimeout(keepAliveTimeout);
                        },
                    });
                });
            };
        };

        const wsClient = createWSClient({
            WebSocket: WS as unknown as typeof WebSocket,
            url: `ws://localhost:3001`,
            onOpen: () => {
                this.socket = wsClient['activeConnection'].ws._socket;
                this.socket?.unref();
            },
            connectionParams: { id: this.id }
        });

        this.trpc = createTRPCClient<AppRouter>({
            links: [
                ensureProcessLives,
                wsLink<AppRouter>({ client: wsClient })
            ],
        });
Was this page helpful?