基于游标的分页
在关系字段上,您可以利用基于游标的分页,这通常与无限滚动应用程序相关联。
使用以下类型定义
type User {
name: String!
posts: [Post!]! @relationship(type: "HAS_POST", direction: OUT)
}
type Post {
content: String!
}
如果要一次获取“John Smith”用户的 10 个帖子,您将首先获取 10 个
query {
users(where: { name: "John Smith" }) {
name
postsConnection(first: 10) {
edges {
node {
content
}
}
pageInfo {
endCursor
hasNextPage
}
}
}
}
在返回值中,如果hasNextPage
为true
,则将endCursor
传递到下一个包含 10 个结果的查询中。您可以像以下示例中那样使用变量来执行此操作
query Users($after: String) {
users(where: { name: "John Smith" }) {
name
postsConnection(first: 10, after: $after) {
edges {
node {
content
}
}
pageInfo {
endCursor
hasNextPage
}
}
}
}
您将继续执行此操作,直到hasNextPage
为false
- 此时表示您已到达数据的末尾。
totalCount
Connection 字段还提供了一个totalCount
字段,可用于计算页码,这在您希望通过游标进行分页但在应用程序中使用页码时非常有用。使用上面的示例,您只需添加totalCount
字段,它将返回与所用过滤器匹配的结果总数,在本例中仅为所有帖子
query Users($after: String) {
users(where: { name: "John Smith" }) {
name
postsConnection(first: 10) {
edges {
node {
content
}
}
pageInfo {
endCursor
hasNextPage
}
totalCount
}
}
}