How to model recursive data structures in GraphQL

I have a tree data structure that I would like to return through the GraphQL API.

The structure is not particularly large (small enough not to be a problem to return it in one call).

The maximum depth of the structure is not specified.

I modeled the structure somehow like:

type Tag{
    id: String!
    children: [Tag]
}

The problem arises when you want to get tags at an arbitrary depth.

To get all children (for example) at level 3, write a query, for example:

{ tags { id children { id children { id } } } }

Is there a way to write a query to return all tags to an arbitrary depth?

If this is not the recommended way to model a structure similar to that described above in the GraphQL API.

+4
source share
1 answer

. , , .

/* 
  Add an argument to your query:
  
  query {
    tags(depth: 3) { 
      id 
      children
    }
  }
*/

export default {
  Query: {
    tags: async (obj, { depth, }, context) => {
      // depending on how you're getting tags, run the function
      // that gets you a list of tags
      const tags = await getTags(obj, { depth, }, context)
        // depending on which ORM you're using, join 
        // `depth` number of times here on `tags.children`
      
      return tags
    }
  }
}
Hide result

, , , , , , .

0

Source: https://habr.com/ru/post/1680063/


All Articles