微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何在 GraphQL 中强制分页

如何解决如何在 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 举报,一经查实,本站将立刻删除。