小编典典
您甚至不需要中继连接来支持分页。您的查询可以简单地接受页码和大小(或限制/偏移量)作为参数并返回列表-
完成。但是,如果您要使用中继连接(例如Book类型),则可以执行以下操作:
Relay relay = new Relay();
GraphQLOutputType book = ...; //build your normal Book object type
GraphQLObjectType bookEdge = relay.edgeType(book.getName(), book, null, Collections.emptyList());
GraphQLObjectType bookConnection = relay.connectionType(book.getName(), bookEdge, Collections.emptyList());
对于带有基本GraphQL的示例,您这里有一个简单的Web应用程序。
连接规范自然适合支持基于光标的分页的数据存储,但是在与不同的分页样式一起使用时需要一些创造力。
1)如果您希望使用基于简单偏移量的分页,则可以决定将其after视为偏移量(意味着将传递一个数字),并将其first视为限制:
SELECT * FROM ORDER BY timestamp OFFSET $after LIMIT $first
before和和相同last,只是方向不同。
2)另一种方法是将after/ before视为sort列的最后一次看到的值(这样将传递实际的(混淆的)值):
SELECT * FROM ORDER BY timestamp WHERE timestamp > $after LIMIT $first
我还建议您使用示例应用程序查看我的项目graphql-spqr,这使开发GraphQL API非常简单。
例如,您将创建如下的分页结果:
public class BookService {
@GraphQLQuery(name = "books")
//make sure the argument names and types match the Relay spec
public Page getBooks(@GraphQLArgument(name = "first") int first, @GraphQLArgument(name = "after") String after) {
//if you decide to fetch from a SQL DB, you need the limit and offset instead of a cursor
//so, you can treat "first" as count as "after" as offset
int offset = Integer.valueOf(after);
List books = getBooksFromDB(first, offset);
Page bookPage = PageFactory.createOffsetBasedPage(books, totalBookCount, offset);
return bookPage;
}
}
创建Page实例还有许多其他方法,这只是最简单的方法。
然后,您将根据Java类生成模式:
GraphQLSchema schema = new GraphQLSchemaGenerator()
.withOperationsFromSingleton(new BookService())
.generate();
GraphQL graphQL = GraphQLRuntime.newGraphQL(schema).build();
并执行查询:
ExecutionResult result = graphQL.execute("{books(first:10, after:\"20\") {" +
" pageInfo {" +
" hasNextPage" +
" }," +
" edges {" +
" cursor, node {" +
" title" +
"}}}}");
但是,再次重申, 如果您不使用Relay,那么实际上就不需要太复杂
。如果您的存储设备自然支持基于游标的分页,请继续使用。如果不是,则只需使用简单的limit /
offset参数并返回一个列表,然后忘记连接规范。创建它是为了使Relay能够在各种情况下自动管理分页,因此如果您不使用Relay和/或具有基于游标的分页的DB,则几乎总是完全无效。
2020-10-15