【问题标题】:Cursor Pagination with Apollo/GraphQL keeps giving me errorApollo/GraphQL 的光标分页不断给我错误
【发布时间】:2017-10-10 17:48:49
【问题描述】:

我正在尝试实现光标分页并按照文档中的示例进行操作,但我一直收到错误消息,提示 'Cannot query field "cursor" on type "Query"'

我知道“光标”字段实际上并不存在于 Accounts 架构中……但是从我从文档中读取的内容来看……您必须将其包含在 gql`` 查询中的某个位置。此外,不确定我是否遗漏了什么,但我对如何构建查询以允许光标分页有点困惑。

原始查询:(运行它不会出错)

const AccountsQuery = gql`
  query {
    accounts {
      accountName
      accountId
    }
  }
`;

新查询:(这会出现“无法在帐户上找到光标字段”错误)

const AccountsQuery = gql`
  query Accounts($cursor: String){
    accounts(cursor: $cursor) {
      cursor
      accountName
      accountId
    }
  }
`;

GraphQL 包装器:

export default graphql(AccountsQuery, {
  props: ({ data: { loading, cursor, accounts, fetchmore } }) => ({
    loading,
    accounts,
    loadMoreEntries() {
      return fetchmore({
        query: AccountsQuery,
        variables: {
          cursor: cursor,
        },
        updateQuery: (previousResult, { fetchMoreResult }) => {
          const previousEntry = previousResult.entry;
          const newAccounts = fetchMoreResult.accounts;

          return {
            cursor: fetchMoreResult.cursor,
            entry: {
              accounts: [...newAccounts, ...previousEntry]
            },
          };
        },
      })
    }
  })
})(QuickViewContainer);

如果能帮助光标分页正常工作,我们将不胜感激!

【问题讨论】:

  • 我认为您缺少服务器中查询定义上的光标。看起来怎么样?

标签: pagination graphql apollo react-apollo


【解决方案1】:

听起来cursor 字段没有在服务器上实现。你的 Account 类型需要有这样的字段:

Account {
  cursor
  accountName
  accountId
}

关于如何进行光标分页的约定,您应该遵循标准的 Relay 规范。您可以在符合 Relay 的 GraphQL API 中read more about how it's implemented here

这将使您的查询看起来像这样:

query {
  viewer {
    allAccounts {
      edges {
        cursor
        node {
          accountName
          accountId
        }
      }
    }
  }
}

每个边缘帐户都有一个对应于节点的游标,并且将使用来自服务器的全局唯一不透明游标 ID 自动填充。

希望这会有所帮助!

【讨论】:

    猜你喜欢
    • 2021-04-09
    • 2020-06-30
    • 2017-06-23
    • 2018-12-27
    • 2017-11-07
    • 2022-01-27
    • 2019-06-12
    • 2018-08-21
    • 2021-02-13
    相关资源
    最近更新 更多