How to resolve fetched fields graphql in spring without checking each field?

How to resolve fetched fields graphql in spring without checking each field?


0

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.

New contributor

Aleksandr is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

2

  • 1

    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.

    – Michel Floyd

    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 difference

    – Jorge Campos

    1 hour ago


Load 3 more related questions


Show fewer related questions

0



Leave a Reply

Your email address will not be published. Required fields are marked *