Search code examples
javagraphqlgraphql-java

Mapping multiple graphQL schema files to separate resolvers - Spring Boot


I'm finding it really difficult to separate queries from one schema file. I want to have something like this:

car.graphqls

type Query {
    car(id: ID!): Car
}

type Car {
    id: ID!,
    name: String!
}

house.graphqls

type Query {
    house(id: ID!): House
}

type House {
    id: ID!,
    owner: String,
    street: String
}

I searched a lot but I can't find a way to write two java classes and implement getHouse() in one of them and getCar() in other.

@Component
public class CarQuery implements GraphQLQueryResolver {

    @Autowired
    private CarService carService;

    public List<Car> getCar(final int id) {
        return this.carService.getCar(id);
    }
}

public class HouseQuery implements GraphQLQueryResolver {

    @Autowired
    private HouseService houseService;

    public List<House> getHouse(final int id) {
        return this.houseService.getHouse(id);
    }
}

I found out that the graphql-java-tools package which I'm using will search through the project and finds all schema files (that end with .graphqls), but the code which I showed above gives me this error:

Caused by: com.coxautodev.graphql.tools.FieldResolverError: No method found with any of the following signatures (with or without one of [interface graphql.schema.DataFetchingEnvironment] as the last argument), in priority order:

  com.example.polls.resolvers.CarQuery.house(~count)
  com.example.polls.resolvers.CarQuery.getHouse(~count)

I also found some advises that I need to have only one Root Query in schema files, and to extend all other Query types in schema files. I tried to write to house.graphqls something like this, but failed:

extend Type Query {
    house(id: ID!): House
}

Is there a way to tell graphql and java what schema file I want to be mapped to which java resolver file?


Solution

  • Multiple schema files

    Graphql-java-tools will find all the .graphqls files to build a schema instance. Multiple schema files work out of the box.

    Multiple resolvers

    Each resolver component must implement GraphQLQueryResolver or GraphQLMutationResolver and be scannable by spring boot. Make sure it has a @Component annotation and is in one of the spring @ComponentScan basePackages.

    The error

    No method found with any of the following signature means that graphql-tools was not able to find a resolver component with a method matching the signatures. In this case, the HouseQuery resolver is missing the @Component annotation.