How to close the websocket connection from client side with apollo link #134
-
Hi, I'm trying to make the websocket connection closed when the tab is idle/hidden, and make it reconnect(lazily) when the tab is active again. I'm wondering how can I do that with graphql-ws on the client side? Thanks! I'm setting up this client following Client Usage with Apollo |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 6 replies
-
Hmm, this would require a combination of a graceful restart and timing the import { createClient } from './client';
// will be reassigned once the client connects
let gracefullyRestart = () => {
// call me when the tab loses focus
};
const client = createClient({
url: 'wss://graceful.restart/is/a/non-fatal/close-code',
retryWait: () =>
new Promise((resolve) => {
// resolve me when the tab gets focus
}),
on: {
connected: (socket) => {
gracefullyRestart = () => {
if (socket.readyState === WebSocket.OPEN) {
socket.close(4205, 'Client Restart');
}
};
},
},
});
// all subscriptions through `client.subscribe` will resubscribe on graceful restarts The client resubscribes only when the socket closes with a non-fatal code, so what you are doing with the above example is performing a graceful restart and making the client retry only when the However, I must say that I absolutely DO NOT recommend doing this! Its very hacky and messes with other types of restarts (like actual connection problems and abrupt closures). Furthermore, I wouldnt ever close a connection just because the browser lost focus. You need the background updates to better the UX and to keep the user up-to-date as much as possible. I must ask, out of curiosity, why would you want to close the connection when the browser tab changes? And a follow-up question, are you sure you really need this? |
Beta Was this translation helpful? Give feedback.
Hmm, this would require a combination of a graceful restart and timing the
retryWait
client option. In essence, something like this: