Best practices
-
Create different resolvers for different types;
type Query { huaweiCars: [HuaweiCar!] volvoCars: [VolvoCar!] }If:
- you expect to add more types(car manufacturer) in the near future. This prevents potential messiness.
- Your client need to perform queries like “sort Huawei cars by their rating ascending, Volvo cars by their ratings descending”.
- Here we just changed one of the parameters. But this can get even messier as decide to change more parameters.
- Though we can solve this by calling our API twice :).
- Here we just changed one of the parameters. But this can get even messier as decide to change more parameters.
[!CAUTION]
If adding separate queries is not doable consider the next suggestion.
-
Homogenize two or more resolvers into a single one with unions. Then to simplify your query you can:
- Filter using arguments.
- Use fragments.
- Use directives.
query GetProducts($clientType: String!) { products { id price inventory @include(if: $clientType == "ADMIN") salesData @include(if: $clientType == "ADMIN") } }
[!NOTE]
Refs of the Best Practices sections:
- Stackoverflow Q&A: Best practice around GraphQL nesting depth.
Just read/watch for fun: