Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect an unsubscribe in Apollo graphql server

In the Apollo server, when a client user subscribes to a subscription (using WebSocket), we can detect this using the subscription resolver.

But is there also a way to detect an unsubscribe? I see the WebSocket sends a {"id": "1", "type": "stop"} message, but I don't know how to catch this

So I don't want to know when a user disconnects from the Websocket, but when a user has unsubscribed a subscription with Apollo client.

like image 202
Jonathan Callewaert Avatar asked Dec 11 '22 02:12

Jonathan Callewaert


1 Answers

I've been having the same issue, cant believe this isn't in-built into GraphQL or covered in the docs.

I found the solution in a github issue which you can read here

the way I fixed it was:

added the withCancel function to my resolver :

const withCancel = (asyncIterator, onCancel) => {
  const asyncReturn = asyncIterator.return;

  asyncIterator.return = () => {
    onCancel();
    return asyncReturn ? asyncReturn.call(asyncIterator) : Promise.resolve({ value: undefined, done: true });
  };

  return asyncIterator;
};

then used that in my subscribe:

Subscription: {
    update: {
      subscribe: (root, { id, topic }, ctx, info) => {
        logger.info(`start new subscription for ${id}`);
        ActiveMQ(id, topic);

        return withCancel(pubsub.asyncIterator(id), () => {
          console.log(`Subscription closed, do your cleanup`);
        });
      },
      resolve: payload => {
        return payload;
      },
    },
  }

Then I handled my logic in the callback provided by withCancel, which for me was closing a stomp client and cleaning up the list of active subscribers etc

like image 161
atmd Avatar answered Feb 19 '23 12:02

atmd