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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With