Reuse existing WebSocket connection if already exists?

In Subscriptions - Apollo GraphQL Docs , the Apollo doc indicates that “Although Apollo Client can use your GraphQLWsLink to execute all operation types, in most cases it should continue using HTTP for queries and mutations.”

To help me understand this better, what are the cases in which the WebSocket connection should be used to execute queries and mutations? For example, if a persistent WS connection can be assumed, would bandwagoning onto it make sense?

The example code underneath the doc also shows the ability to conditionally choose HTTP or WS depending on the operation and type, but it does so somewhat statically; can this be done dynamically (ie, if a websocket connection already exists, to bandwagon onto it)? I may be missing something basic here, but why wouldn’t it use the WS connection if it could confirm that it already exists? Are there any unforeseen downsides with this method? Thanks!

Hello! If you have a persistent WS connection from a subscription or otherwise, yes you can bandwagon onto it to execute queries and mutations. And you can dynamically do so, assuming you can check the status of that connection.

How you check that connection status depends on the subscription library you’re using, but with the newer graphql-ws library, it looks like you can use the on method of the Client you create to listen for events related to connecting and disconnecting.

Following the logic in Split communication by operation, you would alter the split function to check for the presence of an active connection and split based on that instead of strictly on operation type.

I would say that a potential caveat to this approach is unpredictability in debugging—if you’re encountering an issue via one transport method but not the other, it can be trickier than usual to reproduce.