'jpa, graphql: type as input and or output

Graphql Query

type Query {
  filteredPersons(filter: Person) : PersonApi
}

PersonApi

type PersonApi{
  items: [Person]
  total_count: Int
}

Person

type Person{
  id: ID!
  firstName : String
  lastName : String
}

Resolver

public PersonApi filteredPersons(Person filter) {

  ExampleMatcher matcher = ExampleMatcher.matchingAny()
     .withMatcher("firstName", ExampleMatcher.GenericPropertyMatchers.contains().ignoreCase())
     .withMatcher("lastName", ExampleMatcher.GenericPropertyMatchers.contains().ignoreCase()));

  Example<Person> filteredPerson = Example.of(filter, matcher);

  Page<Person> personPage = repository.findAll(example);

  if (personPage != null) {
    return new PersonApi (
        new ArrayList<>(personPage.getContent()),
        NumberUtils.toInt(String.valueOf(personPage.getTotalElements())));
  }
  return new PersonApi(new ArrayList<>(), NumberUtils.INTEGER_ZERO);
  }
}

Repository

@Repository
public interface PersonRepository extends JpaRepository<Person, Integer> {}

As show the code above, I'm trying to make a query with a filter parameter that is a type. Obviously, graphql expect this parameter to be an input.

This mean I have to use a dto (PersonFilter) and translate it into an entity in order to do the query.

  private CsvRawEntity getPersonFrom(PersonFilter filter) {
    Person entity = new Person();
    entity.setFirstName(filter.getFirstName());
    entity.setLastName(filter.getLastName());
    return entity;
  }

  public PersonApi filteredPersons(Person filter) {
    ...
    Person entity = getEntityFrom(filter);
    Example<Person> example = Example.of(entity, customExampleMatcher);

    personPage = repository.findAll(example, pageable);
    PersonApi response = new PersonApi(
        new ArrayList<>(personPage.getContent()),
        NumberUtils.toInt(String.valueOf(personPage.getTotalElements())));
    return response;
  }

(which then work like a charm).

Same issue with outputif my type contains another type.

Question

Is there is a way or trick to make GraphQL to accept a type when it expect an input or an output ?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source