使用来自 apollo-link-ws 的 WebSocketLink 检查互联网连接

check for internet connectivity using WebSocketLink from apollo-link-ws

我正在尝试使用 apollo websockets 检查互联网连接,这样做的目的是在没有连接时显示 "you're disconnected" 消息以防止用户输入并假设更改已保存(更改应该保存在类型上),这是 apollo-link-ws

设置的一部分
const wsLink = new WebSocketLink({
uri: `ws://${hostname}${port ? `:${port}` : ''}/subscriptions`,
options: {
 reconnect: true,
 connectionParams: () => ({
  authorization: localStorage.getItem('accelerator-token')
 })
}
});

    const hasSubscriptionOperation = ({ query: { definitions } }) =>
    definitions.some(
    ({ kind, operation }) =>
      kind === 'OperationDefinition' && operation === 'subscription'
  );

这是客户端配置:

const client = new ApolloClient({
link: ApolloLink.split(
    hasSubscriptionOperation,
    wsLink,
    ApolloLink.from([
      cleanTypenameLink,
      authMiddleware,
      errorLink,
      stateLink,
      createUploadLink()
    ])
  ),
  cache
});

经过一些搜索,我发现我可以使用 subscriptions-transport-ws 中的 SubscriptionClient

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);

这些方法可以用来检测网络状态

如果你正在使用 React,我发现了这个不错的社区包 react-apollo-network-status