Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Using pubsub in onConnect and onDisconnect #247

Closed
1 of 4 tasks
merpig opened this issue Nov 4, 2021 · 0 comments
Closed
1 of 4 tasks

Using pubsub in onConnect and onDisconnect #247

merpig opened this issue Nov 4, 2021 · 0 comments

Comments

@merpig
Copy link

merpig commented Nov 4, 2021

  • has-reproduction
  • feature
  • blocking
  • good first issue

I've done a good bit of research on using pubsub in the SubscriptionServer onConnect and onDisconnect methods and haven't found any ways to do this or work arounds. I'm wanting to publish events to other clients when subscriptions open/close with a specific client.

Example of what I would like to be able to do

const subscriptionServer = SubscriptionServer.create({
  schema,
  context: authMiddleware,
  execute,
  subscribe,
  onConnect(connectionParams) {
    const token = connectionParams.authToken.split(' ').pop().trim();
    if(token){
      try {
        const { data } = jwt.verify(token, secret, { maxAge: expiration });
        console.log(`${data.username} has connected`);
        
        // I would like to publish this event to the subscriptions in my resolvers
        pubsub.publish('USER_CONNECTED', {/* data to be passed */});
        return data
      } catch {
        console.log('Invalid token');
      }
    }
    return false;
  },
  onDisconnect(_,context){
    context.initPromise.then( async user=>{
      if(user){
        console.log(`${user.username} has disconnected`)
        
        // I would like to publish this event to the subscriptions in my resolvers
        pubsub.publish('USER_DISCONNECTED', {/* data to be passed */});
      }
    })
  }
}, {
  server: httpServer,
  path: server.graphqlPath
});

My resolvers look like:

const resolvers = {
  Query: {...},
  Mutation: {...},
  Subscription: {
    loggedIn: {
      subscribe: withFilter(
        ()=> pubsub.asyncIterator('USER_CONNECTED'),
        ({data},_,context)=> {
          return data.includes(context.username)
        }
      )
    },
    loggedOut: {
      subscribe: withFilter(
        ()=> pubsub.asyncIterator('USER_DISCONNECTED'),
        ({data},_,context)=> {
          return data.includes(context.username)
        }
      )
    }
  }
}
@merpig merpig closed this as completed Nov 13, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant