'Query circular attribute in graphql

I have the following scheme

type Product {
   code: ID!
   services: [ServiceGroup]
}

type ServiceGroup {
   code: String!
   options: [ServiceItem]
}

type ServiceItem {
   itemName: String!
   groups: [ServiceGroup]
}

Now in the client, how can I query a product and its services considering that groups is nested with more groups.

gql`
 query getProduct($code: ID!) { 
     product(code: $code) {
        code
        services {
           code
           options {
               itemName
               groups {
                  code
                  options {
                    ....
                  }
                }
            }
        }
     }
  }
`
              


Solution 1:[1]

The problem is that gql does not allow the nesting of recursive fragments. In the provided example you have a circular dependency which gql cannot handle. The article provided shows an approach with a finite recursive depth.

  • Workarounds would be to fetch only identifies such as code or itemName and refetching those objects when needed.
  • If the entire structure is needed as one object you might consider to fetch the structure as a JSON object (encoded as String) and parsing it locally. Using this method is not type safe!

Solution 2:[2]

The query would have to be dynamically written in the client based on what the depth is. You could have another query field that returns this.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Kn3cht
Solution 2 Ricardo Portugal