All Downloads are FREE. Search and download functionalities are using the official Maven repository.

graphql.annotations.connection.PaginatedDataConnectionFetcher Maven / Gradle / Ivy

There is a newer version: 21.5
Show newest version
/**
 * Copyright 2016 Yurii Rashkovskii
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 */
package graphql.annotations.connection;

import graphql.relay.*;
import graphql.schema.DataFetcher;
import graphql.schema.DataFetchingEnvironment;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;

/**
 * Use this class in {@link GraphQLConnection} to do a real pagination,
 * i.e you fetch each time the relevant data, you make the cursors and
 * you decide if there are previous or next pages
 * 

* Note: If you are using the connection, the return type of the associated dataFetcher must implement {@link PaginatedData} * * @param the entity type that is paginated */ public class PaginatedDataConnectionFetcher implements ConnectionFetcher { private DataFetcher> paginationDataFetcher; public PaginatedDataConnectionFetcher(DataFetcher> paginationDataFetcher) { this.paginationDataFetcher = paginationDataFetcher; } @Override public Connection get(DataFetchingEnvironment environment) throws Exception{ PaginatedData paginatedData = paginationDataFetcher.get(environment); if (paginatedData == null) { return new DefaultConnection<>(Collections.emptyList(), new DefaultPageInfo(null,null,false,false)); } List> edges = buildEdges(paginatedData); PageInfo pageInfo = getPageInfo(edges, paginatedData); return new DefaultConnection<>(edges, pageInfo); } private PageInfo getPageInfo(List> edges, PaginatedData paginatedData) { if (edges.isEmpty()) { return new DefaultPageInfo(null,null,false,false); } ConnectionCursor firstCursor = edges.get(0).getCursor(); ConnectionCursor lastCursor = edges.get(edges.size() - 1).getCursor(); return new DefaultPageInfo( firstCursor, lastCursor, paginatedData.hasPreviousPage(), paginatedData.hasNextPage() ); } private List> buildEdges(PaginatedData paginatedData) { Iterator data = paginatedData.iterator(); List> edges = new ArrayList<>(); for (; data.hasNext(); ) { T entity = data.next(); edges.add(new DefaultEdge<>(entity, new DefaultConnectionCursor(paginatedData.getCursor(entity)))); } return edges; } }





© 2015 - 2024 Weber Informatics LLC | Privacy Policy