I'm trying to check for internet connectivity using apollo websockets, the purpose of this is to show a "you're disconnected" message when there is no connection to prevent the user from typing and assuming the changes are saved (the changes are supposedly saved on type), here's part of the setup of apollo-link-ws
const wsLink = new WebSocketLink({
uri: `ws://${hostname}${port ? `:${port}` : ''}/subscriptions`,
options: {
reconnect: true,
connectionParams: () => ({
authorization: localStorage.getItem('accelerator-token')
})
}
});
and
const hasSubscriptionOperation = ({ query: { definitions } }) =>
definitions.some(
({ kind, operation }) =>
kind === 'OperationDefinition' && operation === 'subscription'
);
and here's the client config:
const client = new ApolloClient({
link: ApolloLink.split(
hasSubscriptionOperation,
wsLink,
ApolloLink.from([
cleanTypenameLink,
authMiddleware,
errorLink,
stateLink,
createUploadLink()
])
),
cache
});
Instead, Apollo Client subscriptions most commonly communicate over WebSocket, via the graphql-ws library. As mentioned in Choosing a subscription protocol, some servers use an older library called subscriptions-transport-ws .
HttpLink is a terminating link that sends a GraphQL operation to a remote endpoint over HTTP. Apollo Client uses HttpLink by default when you provide the uri option to the ApolloClient constructor. HttpLink supports both POST and GET requests, and you can configure HTTP options on a per-operation basis.
Luckily, Apollo provides a nice way for authenticating all requests by using the concept of middleware, implemented as an Apollo Link. import { setContext } from '@apollo/client/link/context'; This middleware will be invoked every time ApolloClient sends a request to the server.
The WebSocketLink is a terminating link that's used most commonly with GraphQL subscriptions (which usually communicate over WebSocket), although you can send queries and mutations over WebSocket as well.
After some searching i found that i can use SubscriptionClient from subscriptions-transport-ws
export const myClient = new SubscriptionClient(`ws://${hostname}${port ?
`:${port}` : ''}/subscriptions`, {
reconnect: true,
connectionParams: () => ({
authorization: localStorage.getItem('accelerator-token')
})
});
myClient.onConnected(()=>{console.log("connected f client f onConnected")})
myClient.onReconnected(()=>{console.log("connected f client f
reconnected")})
myClient.onReconnecting(()=>{console.log("connected f client f
reconnecting")})
myClient.onDisconnected(()=>{console.log("connected f client f
onDisconnected")})
myClient.onError(()=>{console.log("connected f client f onError")})
export const wsLink = new WebSocketLink(myClient);
These methods can be used to detect the network status
If you are working with React I found this nice community package react-apollo-network-status
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With