0

I have a social network kind of web app which includes graphql by react-apollo-client (my graphql server is a Hasura instance).
I have notifications feature in my app and I query the notifications details together with count aggregation to show the user how many notifications he has before displaying it.

Recently I added web sockets to my app and refactor my notifications query to be a subscribtion. It works just fine - when new notification was inserted to the DB the subscription gets called instantly.
My problem is the count aggregation. When I run the following subscription:

const GET_NOTIFICATIONS = gql`
subscription($userId: Number!) {
  notifications(where: { user_id: { _eq: $userId } }) {
    creation_time
    description
  }
  notifications_aggregations (where: { user_id: { _eq: $userId } }) {
    aggregate {
      count
    }
}
`

I am getting the following error - {"type":"subscription_data","id":4,"payload":{"errors":[{"message":"Subscription \"A\" must select only one top level field.","locations":[{"line":7,"column":3}]}]}}

After quick research I still could not find any solution to my problem.
Is there a way for my to keep the count aggregation in my subscribtion? Or do I need to count the notifications number myself after the subscription called?

Thanks for every response.

Itamar Smirra
  • 83
  • 1
  • 7

1 Answers1

0

As the error states, a subscription is only allowed to have a single top level selection. To work around this, you can just split it into two separate subscriptions.

It probably makes more sense to hoist the notification count higher up in the application context anyways so that you can display the total count of notifications in the app header for example. If you do this I'd suggest that you can convert the part of the operation that actually retrieves the notifications back into a query instead and only call it when the user actually attempts to view the notifications to save on the overhead.

Jesse Carter
  • 20,062
  • 7
  • 64
  • 101
  • This means 2 requests to the graphql engine instead of 1, which i tried to avoid. Don't you think it is better to get the notifictions as is and calculate the count number by the array length? – Itamar Smirra Oct 27 '21 at 15:56