Search code examples
mongodbgraphqlapolloreact-apolloapollo-server

How do I get GraphQL to get live/new data from database without polling?


I have a backend running GraphQL, MongoDB + Mongoose, and Apollo. This application has functionality for user accounts and a friends list. Each user can login to their account and see a list of friends with their current 'status'; If a friend changes their status, I need that change to be reflected on the user's side. An example of this is like facebook's "green dot" on messenger that tells you when one of your friends is online using the application.

I have been searching documentation for GraphQL and have been suggested either Subscriptions or Live Queries. Subscriptions seem to be the majority of suggestions from what I understand, live queries are not officially part of GraphQL or were dropped.

Does anyone have a solution to getting "live" data with GraphQL/MongoDB that doesn't involve polling for this scenario?


Solution

  • You already seem to have your answer: subscriptions!

    Using your example, consider two users - mikep17 and mcy. You are mikep17, logged into your application and viewing your list of friends and their statuses. I am your friend, and I log in as you are viewing this list, and you want to see that in your application's UI.

    On the frontend, in your application's instance, your application will execute a subscription to some event. Let's call it friendStatusChange. Now your application is "listening" for that event in order to respond accordingly. Let's assume that when your application receives the event, it can parse out the information that "I" (mcy) have changed from offline => online and then use that to add the "green dot" next to my username.

    On the backend, your GraphQL server will have code that handles your user functionality - logging in, logging out, etc. It will need to be enhanced to hook into these actions and "publish" the friendStatusChange event as applicable.

    Now, instead of your client constantly asking (polling) "did a friend's status change? how about now? now?", it can just listen and wait for your server to tap it on the shoulder and say "hey buddy, your friend mcy's status changed".