当具有开放订阅的客户端无法访问时,如何从 ApolloServer启用 keepAlive获得通知?

问题描述

我有一个带有 apollo-server 的应用程序,它使用 apollo-client 处理多个客户端设备以建立 websocket 订阅

  • 当客户端连接到服务器时,会按预期调用“onConnected”钩子。
  • 当客户端与服务器断开连接时,会按预期调用“ondisconnected”钩子。

对于这两个事件,我可以根据设备连接状态更新相关数据库

ApolloServer 配置为为开放订阅启用 keepAlive,以便客户端可以检测到服务器已关闭或无法访问,并且这在客户端级别工作。

但是,如果客户端变得无法访问(例如以太网电缆断开),我希望在服务器级别收到通知,但如果发生这种情况,我永远不会得到任何信息来了解这种情况,并且我无法将相关数据库更新为反映设备连接状态。

有没有办法实现这个目标?

代码如下:

const server = new ApolloServer({
  typeDefs: typeDefs,schemaDirectives: {
    role: RoleDirective
  },resolvers,context: async ({req,connection}) => {

    if (connection) {
      console.log('CONNECT with connection')

      return connection.context

    } else if (req) {
      console.log('CONNECT with request')

      let token = req.headers.authorization || '';

      return await createContextFromrequest(req,token)

    } else {
      console.log('CONNECT with no request OR connection\n')
    }
  },subscriptions: {
    keepAlive: 10000,onConnect: async (connectionParams,websocket,context) => {
      console.log('Websocket CONNECTED')

      let token = connectionParams.authorization || ''

      return await createContextFromrequest(context.request,token)
    },ondisconnect: (websocket,context) => {
      console.log('Websocket disCONNECTED\n')
    }
  }
})

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)