3 ms·
There are basically two approaches to this issue: 0) Do nothing If you are just prototyping, you should do the simplest thing that could possibly work. (But t
by sorenbs 9y ago
There are basically two approaches to this issue:
0) Do nothing
If you are just prototyping, you should do the simplest thing that could possibly work. (But this is not a real solution, so I won't count it)
2) Request Batching
This approach is popularised by Facebooks Dataloader library https://github.com/facebook/dataloader https://github.com/facebook/dataloader
Instead of directly querying the database in the resolver, you return a specification of what data you are interested in. When all resolvers on the same level in the query has returned this specification, the Dataloader library figures out how to batch queries together as much as possible
3) Big Join
You can inspect the GraphQL query in the top level resolver and basically perform one giant join up front. You will then pass the entire value down your resolve hierarchy, and all they have to do is pick out the correct data from the complete result set. Take a look at join-monster if you are interested in this approach.
The Graphcool hosted backend is serving millions of requests an hour using the Dataloader approach, and we have found this to be more flexible and more performant at scale than generating a big complex join up front.
For most queries we see single digit millisecond response time for a batched query, and the time complexity scales linearly with the depth of the query, which is not the case for joins.
- zackify 9y ago2) is easy, but leads to two queries no matter what, because you have to do a whereIn 3) here's the code: const EagerQL = (info, allowed) => { let fields = info.operation.selectionSet.selections[0].selectionSet.selections; return fields .map(field => field.name.value) .filter(field => allowed.includes(field)); }; // in a resolver user(_, args, context, info) { let eagers = EagerQL(info); console.log(eagers); // ['posts'] } This will give you fields that were queried for so you can do a big join. Hope this helps someone :P
- joesb 9y agotrying to access fields like `info.operation.selectionSet.selections[0].selectionSet.selections` always feel wrong to me. I wish graphql library part comes with some utility function for these.
- zackify 9y agoCompletely agree.... I don't understand why there isn't a more standard way of accessing the fields queried for so that you can do joins.
- obi1kenobi 9y agoThe GraphQL compiler project also implements the 3) approach: https://github.com/kensho-technologies/graphql-compiler https://github.com/kensho-technologies/graphql-compiler Primer on how to use it: https://blog.kensho.com/compiled-graphql-as-a-database-query-language-72e106844282 https://blog.kensho.com/compiled-graphql-as-a-database-query... Full disclosure: I wrote it, and open-sourced it just yesterday.