Multi-Query Pagination


GraphQLQueryPager supports multi-query pagination. This means that you can use separate queries for fetching the initial page of data and for fetching subsequent pages of data.

In order to use multi-query pagination, you must configure the GraphQLQueryPager in order to support multiple queries. It is recommended to use an appropriate convenience initializer to create the GraphQLQueryPager instance. The initalizers that support multi-query pagination will have both an extractInitialPageInfo and extractNextPageInfo function.

In the following example, we will initialize a GraphQLQueryPager that uses forward cursor-based pagination.

Swift
1let initialQuery = MyQuery(first: 10, after: nil)
2let pager = GraphQLQueryPager(
3    client: client,
4    initialQuery: initialQuery,
5    extractInitialPageInfo: { initialQueryData in
6        // Extract a `CursorBasedPagination.Forward` instance from the initial query's `Data`
7        CursorBasedPagination.Forward(
8             hasNext: initialQueryData.values.pageInfo.hasNextPage ?? false,
9             endCursor: initialQueryData.values.pageInfo.endCursor
10         )
11    },
12    extractNextPageInfo: { paginatedQueryData in
13        // Extract a `CursorBasedPagination.Forward` instance from the paginated query's `Data`
14        CursorBasedPagination.Forward(
15             hasNext: paginatedQueryData.values.pageInfo.hasNextPage ?? false,
16             endCursor: paginatedQueryData.values.pageInfo.endCursor
17         )
18    },
19    pageResolver: { page, paginationDirection in
20        // As we only want to support forward pagination, we can return `nil` for reverse pagination
21        switch paginationDirection {
22        case .next:
23            return MyPaginatedQuery(first: 10, after: page.endCursor ?? .none)
24        case .previous:
25            return nil
26        }
27    }
28)

This example demonstrates how to create a GraphQLQueryPager that uses separate queries for fetching the initial page of data and for fetching subsequent pages of data. The GraphQLQueryPager is configured to use forward cursor-based pagination. The extractInitialPageInfo and extractNextPageInfo closures are used to extract pagination information from the initial page of data and from the next page of data, respectively. The pageResolver closure is used to resolve the next page query given a CursorBasedPagination.Forward instance.

The GraphQLQueryPager instance can be used in the same way as a single-query pager. The loadNextPage method will automatically use the pageResolver closure to fetch the next page of data.

Feedback

Edit on GitHub

Forums