简体   繁体   中英

GraphQL Spring-boot Query filtering

I'm using the GraphQL Spring-boot library to build a GraphQL API https://github.com/graphql-java/graphql-spring-boot

I have a schema

type Car {
    id: ID!
    model: String
    brand: String
}

type Query {
    allCars: [Car]!
}

And my query is implemented in a Query class in my Spring Boot project

@Component
public class Query implements GraphQLQueryResolver {

public List<Machine> allCars() {}

}

My question is:

How do I use filters and sorting when returning lists:

allCars(first:3){id model}

allCars(filter: {....}){}

I guess this is something that has to be implemented in the Java method, but i'm unsure how to inject the filters etc. in the method.

My guess is that you would create your own filter input type, for example:

type Query {
    allCars(filter: CarsFilter!): [Car]
}


input CarsFilter {
    color: String!
    brand: String!
}

After that, you can write a Java implementation of CarsFilter , for example:

public class CarsFilter {
    private String color;
    private String brand;

    // Getters + Setters
}

Now you can write your resolver using the CarsFilter class:

public List<Car> allCars(CarsFilter filter) {
    // Filter by using JPA specifications, custom queries, ...
}

GraphQL allows for the client to specify exactly what data is desired but it doesn't has any inbuilt way of filtering and sorting the data. You will have write code for that yourself. Regarding injecting the filters, one possible way of doing it can be following:

type Query {
    allCars(filter: String, range: String, sort: String): [Car]!
}

For above Query, sample request would be like:

{
    allCars(filter: "{brand: 'Abc'}", range: "[0, 100]", sort: "[id, ASC]") { # Fetch first 100 cars of brand 'Abc' sorted by id
        id
        model
        brand
    }
}

Then your getAllCars method would be like following:

public List<Car> getAllCars(String filter, String range, String sort) {
    // Implement parser and filter by using JPA specifications
}

To see a sample implementation of parser and its conversion it to JPA specifications, please refer to following project: https://github.com/jaskaransingh156/spring-boot-graphql-with-custom-rql

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM