基于游标的分页

这是 GraphQL 库版本 6 的文档。有关长期支持 (LTS) 版本 5,请参阅 GraphQL 库版本 5 LTS

在关系字段上,您可以利用基于游标的分页,这通常与无限滚动应用程序相关联。

使用以下类型定义

type User @node {
    name: String!
    posts: [Post!]! @relationship(type: "HAS_POST", direction: OUT)
}

type Post @node {
    content: String!
}

如果您想一次获取 10 个“John Smith”用户的帖子,您将首先获取 10 个

query {
    users(where: { name_EQ: "John Smith" }) {
        name
        postsConnection(first: 10) {
            edges {
                node {
                    content
                }
            }
            pageInfo {
                endCursor
                hasNextPage
            }
        }
    }
}

在返回值中,如果 hasNextPagetrue,则将 endCursor 传递到下一个包含 10 个结果的查询中。您可以使用变量来执行此操作,如下例所示

query Users($after: String) {
    users(where: { name_EQ: "John Smith" }) {
        name
        postsConnection(first: 10, after: $after) {
            edges {
                node {
                    content
                }
            }
            pageInfo {
                endCursor
                hasNextPage
            }
        }
    }
}

您将继续这样做,直到 hasNextPagefalse - 这时您已到达数据的末尾。

totalCount

Connection 字段还提供了一个 totalCount 字段,可用于计算页码,这在您想使用游标进行分页但在应用程序中使用页码时很有用。使用上面的示例,您只需添加 totalCount 字段,它将返回与所用过滤器匹配的结果总数,在本例中将是所有帖子

query Users($after: String) {
    users(where: { name_EQ: "John Smith" }) {
        name
        postsConnection(first: 10) {
            edges {
                node {
                    content
                }
            }
            pageInfo {
                endCursor
                hasNextPage
            }
            totalCount
        }
    }
}