I’m learning GraphQL and decided to develop a small application using GraphQL, Spring Boot 3.1.3, Java 20, and the spring-boot-starter-graphql library.
One of the main features of GraphQL is the ability to specify which fields are needed. I found a simple solution to implement this in Java using a field fetcher by checking if a field is required:
FetchingFields fields = context.getFetchedFields();
List<Car> cars = new ArrayList<>();
if (fields.contains("engine")) // do something and get engine for cars
if (fields.contains("wheels")) // add wheels information to cars list
if (fields.contains("price")) // get price and add to list
However, I don’t like this solution because it’s not scalable. I don’t want to have a method with 50 if-statements.
What is the best way to handle fetched fields in GraphQL when working with Spring Boot? Are there any patterns or libraries that can simplify this process and make it more scalable?
I’d be grateful for any recommendations and best practices to create an efficient and maintainable solution for fetching the required fields in my GraphQL application.
2
A good GraphQL server should already be doing this for you automatically. Field-level resolvers should only be called if that field is being requested.
1 hour ago
Given the comments in your code you need the code to "do something" either way. You can use optional, something like:
Optional.ofNullable(fields.get("engine")).ifPresent(f -> doSomething(f));
but again, no difference1 hour ago