I have a tree data structure that I would like to return via a 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 set.
I have modeled the structure as something like:
type Tag{
id: String!
children: [Tag]
}
The problem appears when one wants to get the tags to an arbitrary depth.
To get all the children to (for example) level 3 one would write a query like:
{
tags {
id
children {
id
children {
id
}
}
}
}
Is there a way to write a query to return all the tags to an arbitrary depth?
If not what is the recommended way to model a structure like the one above in a GraphQL API.
Your best bet is to pass a parameter and use that parameter in your resolver. Your syntax will vary depending on which pattern you adopted, but this is the gist of it.
Obviously, any time you recursively query like this, you're risking a database explosion, but as long as you know what you're doing, it should be fine.
Some time ago I came up with another solution, which is the same approach like @WuDo suggested.
The idea is to flatten the tree on data level using IDs to reference them (each child with it's parent) and marking the roots of the tree, then on client side build up the tree again recursively.
This way you should not worry about limiting the depth of your query like in @samcorcos's answer.
schema:
response:
client tree buildup: