Spring GraphQL and org.springframework.data.domain.Sort as controller method argument

90 Views Asked by At

While implementing pagination & reading spring for graphql documentation, I came across the following There is built-in support for Spring Data’s Sort as a controller method argument. For this to work, you need to have a SortStrategy bean.

Could someone perhaps explain a bit more or show some pseudo code?

Thanks a lot

1

There are 1 best solutions below

0
Andy On

I was able to solve the above, here what I did.

1. In my graphql schema file, I made the following changes

users(first:Int, after:String, last:Int, before:String, sort: [String], direction: Direction): UserCConnection
   
enum Direction {
  ASC
  DESC
}

2. Defined the bean as suggested in the spring for graphql documentation

@Bean
    SortStrategy sortStrategy() {
        
        return new AbstractSortStrategy() {
            
            @Override
            protected List<String> getProperties(DataFetchingEnvironment environment) {
                return environment.getArgument("sort");
            }
            
            @Override
            protected Direction getDirection(DataFetchingEnvironment environment) {
                return Direction.fromOptionalString(environment.getArgument("direction")).orElse(null);
            }
        };
    }

3. Made following changes to my controller

@QueryMapping
Window<User> users(ScrollSubrange subrange, Optional<Sort> sort) {
   return service.getUsers(subrange, sort);
}

Points specific to my solutionar are that I am using pagination so if thats not the case with you then it would be Schema:

users(sort: [String], direction: Direction): [User]

Controller:

@QueryMapping
List<User> users(Optional<Sort> sort) {
    return service.getUsers(subrange, sort);
}

I hope this is helpful to you