Skip to content

Reevaluate WebSocket Subscription Input Payload on Reconnection #1574

Closed

Description

@jlalmes

I'm setting up a WS subscription was hoping that when the trpcWsClient reconnects it would re-evaluate the subscription payload, however this is not the case.

- Requirement

  • Create trpc subscripion with { sessionId: null }
  • Server returns { data: { sessionId: 'abc123' } } to the client
  • Trpc connection dies due to bad network connection
  • Trpc reconnects & restablishes subscription with { sessionId: 'abc123' }

The code shown below is my current workaround:

// client.ts
import type { Router } from 'apps/api/src';

import { createTRPCClient } from '@trpc/client';
import { createWSClient, wsLink } from '@trpc/client/links/wsLink';

const wsClient = createWSClient({ url: 'ws://localhost:8081' });

const trpcWsClient = createTRPCClient<Router>({
  links: [
    wsLink({ client: wsClient }),
  ],
});

let sessionId: string | null = null;

const subscribe = () => {
  const unsubcribe = trpcWsClient.subscription('session', { sessionId }, {
    onNext: (result) => {
      if (result.type === 'data') {
        sessionId = result.data.sessionId;
      }
    },
    onError: (error) => {
      console.error(error);
      unsubcribe();
      subscribe();
    },
  });
};

subscribe();

- Solution proposal

  • Modify the trpc client .subscription API
  • Can accept TInput or () => TInput
  • If input is function it is resolved on each reconnection

Example usage:

// client.ts
import type { Router } from 'apps/api/src';

import { createTRPCClient } from '@trpc/client';
import { createWSClient, wsLink } from '@trpc/client/links/wsLink';

const wsClient = createWSClient({ url: 'ws://localhost:8081' });

const trpcWsClient = createTRPCClient<Router>({
  links: [
    wsLink({ client: wsClient }),
  ],
});

let sessionId: string | null = null;

trpcWsClient.subscription('session', () => ({ sessionId }), {
  onNext: (result) => {
    if (result.type === 'data') {
      sessionId = result.data.sessionId;
    }
  }
});

Let me know what you think @KATT

Activity

  1. jlalmes commented on Mar 1, 2022

    @jlalmes
    ContributorAuthor

    PR opened here: #1584

  2. github-actions commented on Oct 4, 2022

    @github-actions
    Contributor

    This issue has been locked because it had no new activity for 14 days. If you are running into a similar issue, please create a new issue. Thank you.

  3. locked as resolved and limited conversation to collaborators on Oct 4, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions