2
votes

Working with GraphQl subscriptions I`m facing a curious issue. For purpose of real-time updates, I use MongoDB Change Stream feature on a server (NodeJs) and GraphQl subscriptions for front-end (Angular). So, when some changes appear in database its send to a client-side by GraphQl subscriptions. On the Angular component, there is the GraphQl subscription implementation (use Apollo client):

...
ngOnInit() {
    this.subscribeToApprovedNews(this.params);
}

subscribeToApprovedNews(params) {
  this.newsQuery.subscribeToMore({
      document: addApprovedNews,
      variables: {
        projectId: params
      },
      updateQuery: (previous, { subscriptionData }) => {
        ...
        const newItem = subscriptionData.data['addApprovedNews'];
        console.log(`${params} -> added news -> ${newItem}`);
        ...
      }
  });
}

But when we enter to this component n times, on one change in database we receive data from subscription this n times. As I understand when we entering the component the client has established new WebSocket connection: "Network" tab of the Chrome developer tools As transport for GraphQL subscriptions I use subscriptions-transport-ws package.

So, one change on database fire multiple QraphQl subscription resolvers and as a result on client-side we receive duplicated notification about change. How it`s possible to fix this behaviour and to recieve only one data per subscription no matter how many times the user enters to the component?

Thank you in advance!

1

1 Answers

0
votes

I think you should unsubscribe when you leave component. Good place is ngOnDestroy method.