Facebook flaunted ability to commit recursive queries when opening graphql, I'm struggling to find documentation that permits you to do it efficiently (networking wise) and easily.
To be precise I'd like query child (name) > name child (curName) [ name child ...] potentially until I exhaust the whole tree without entering arbitrary number of branches within query itself if its possible.
The field resolver actually solve it. There are basically two kinds of queries in graphql server, one is root query resolver, and the other is the field resolver. See the following example in apollo, but the idea behind is the same:
type Person {
name: String
friends: [Person]
}
type Query {
allPeople($name: String):[Person]
}
schema {
query: Query
}
Based on the above typedef, you can write a root query resolver like below:
{
Query: {
allPeople: (root, args) => PersonModel.find({where: {name: args.name}})
}
}
And you also need to write a resolver for the friends
field like below:
{
Person: {
friends: (root, args) => PersonModel.find({where: {friendId: root.id}})
}
}
Because of the field resolver, it can go infinite nesting.
By the way, in order to avoid too many sql statements hitting db, we can introduce dataloader
package which is from facebook it can combine all queries in one async chain into one batch query we provide when initialising dataloader
.
The code above is kind of pseudocode, hope it explained well.
Cheers, Ron