Online User Tracking with GraphQL Apollo

I need to handle the events "user is online now" and "user is now disconnected" on the GraphQL server Apollo Node.js. What is the best way to do this?

My investigation . I am sure that I do not need to implement the beat logic because subscribers are working on WebSockets. But I did not find in my documents information on how to handle WebSockets events, such as “connect” and “disconnect” from the subscription ... In fact, I can process these events from outside the actual subscription:

SubscriptionServer.create({
    execute,
    subscribe,
    schema,
    onConnect = (...args) => {
        console.log('User connected')
    },
    onDisconnect = (...args) => {
        console.log('User disconnected')
    }
}, {
    server: ws,
    path: '/subscriptions'
})

But it cannot determine which user is connected through this socket.

My implementation : so far I have done it like this:

  • , jsonwebtoken req. " ".

  • , . , , , :

    userOnlineSubscription: {
        subscribe: withFilter(
            () => pubSub.asyncIterator('userOnlineSubscription'),
                async (payload, variables) => {
                    if (!payload) {
                        // set user offline
                }
                return false
            }
        )
    }
    

, . - ?

+4
1

onConnect (connectionParams, webSocket) {
  const userPromise = new Promise((resolve, reject) => {
    if (connectionParams.jwt) {
      jsonwebtoken.verify(
        connectionParams.jwt,
        JWT_SECRET,
        (err, decoded) => {
          if (err) {
            reject(new Error('Invalid Token'))
          }

          resolve(
            User.findOne({
              where: { id: decoded.id }
            })
          )
        }
      )
    } else {
      reject(new Error('No Token'))
    }
  })

  return userPromise.then(user => {
    if (user) {
      return { user: Promise.resolve(user) }
    }

    return Promise.reject(new Error('No User'))
  })
}
+1

Source: https://habr.com/ru/post/1692406/


All Articles