如何在 GraphQL 中强制分页

问题描述

我在 GraphQL API 中看到很多,当从查询获取对象列表时,必须提供“第一个”或“最后一个”元素。我知道这是由于分页机制的实现。查询的“first”和“last”参数是强制性的。例如,在 Saleor API 中,我可以使用

查询前 10 个产品
{
  products(first: 10) {
    edges {
      node {
        id
        name
        description
      }
    }
  }
}

当我忽略产品查询的“第一个”参数时,我会收到错误

"您必须提供 firstlast 值才能正确分页 products 连接。”

我在想也许参数是强制性的,那就是必须有一个“!”在产品查询定义中的“first”和“last”之后。但是,检查架构我发现了产品查询的定义:

products(
    # Filtering options for products.
    filter: ProductFilterInput
    # Sort products.
    sortBy: ProductOrder
    # [Deprecated] Filter products by stock availability. Use the `filter` field
    # instead. This field will be removed after 2020-07-31.
    stockAvailability: StockAvailability
    # Return the elements in the list that come before the specified cursor.
    before: String
    # Return the elements in the list that come after the specified cursor.
    after: String
    # Return the first n elements from the list.
    first: Int
    # Return the last n elements from the list.
    last: Int
  ): ProductCountableConnection

似乎参数不是强制性的,但只要我在产品查询中不包含至少两个参数中的一个,就会显示上述错误

我目前正在使用 Apollo Server 实现我自己的 GraphQL API,我也使用分页。我也想强制执行这种行为!有没有标准的方法来做到这一点,或者做一些常见的 GraphQL 实现可能会自动检测分页并强制执行?

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)