How to provide Total number of rows while using PageFactory.createOffsetBasedPage

64 views Asked by At

As per the relay specs, total number of rows should be provided in the connection itself. But I couldn't find a way to provide total number of rows or page count etc...

https://graphql.org/learn/pagination/

I am referring below sample provided for relay based pagination.

https://github.com/leangen/graphql-spqr-samples/blob/master/spring-boot-starter-sample/src/main/java/io/leangen/graphql/samples/repo/ProjectRepo.java

1

There are 1 answers

2
kaqqao On

That's a curious case. Relay Connection spec actually does not mention totalCount in the Connection object, but their examples randomly include that field anyway.

Either way, you can extends SPQR's Page as you see fit. You can have a look at the testExtendedPageMapping test which makes use of a custom ExtendedPage.

The resolver itself looks like this:

@GraphQLQuery(name = "extended")
public ExtendedPage<Book> getExtended(
                              @GraphQLArgument(name = "first") int limit,
                              @GraphQLArgument(name = "after") String after) {
    long offset = Long.parseLong(after);
    List<Book> books = db.queryForBooks(limit, offset);
    long totalCount = db.getTotalCount();
    //Create ExtendedPage that has totalCount field
    return PageFactory.createOffsetBasedPage(books, totalCount, offset, 
                (edges, info) -> new ExtendedPage<>(edges, info, totalCount));
}

ExtendedPage is a simple implementation of Page:

public class ExtendedPage<N> implements Page<N> {

    private final List<Edge<N>> edges;
    private final PageInfo pageInfo;
    private final long totalCount;

    ExtendedPage(List<Edge<N>> edges, PageInfo pageInfo, long totalCount) {
        this.edges = edges;
        this.pageInfo = pageInfo;
        this.totalCount = totalCount;
    }

    @Override
    public List<Edge<N>> getEdges() {
        return edges;
    }

    @Override
    public PageInfo getPageInfo() {
        return pageInfo;
    }

    public long getTotalCount() {
        return totalCount;
    }
}