GraphQL、Shopify 获取所有产品或产品总数

noo*_*der 11 shopify graphql

我是 graphQL 的新手,我必须检索所有产品。我一直在环顾四周,观看教程和阅读,人们似乎返回了他们想要的所有某种类型的数据,但我不能。例如,它会抛出一个错误,指出您必须提供第一个或最后一个,但我想要全部,否则它会说totalCount或count不存在。

\n
 {\n  products {\n    id\n    title\n    price\n    \n  }\n}\n\n// or get total count of products\n\n {\n  products {\n   totalCount\n  }\n}\n
Run Code Online (Sandbox Code Playgroud)\n

我基本上是在尝试做类似的事情。我知道我可能不会收到任何帮助,因为没有人可以访问我的 shopify admin api,但甚至可能是一个示例或我可以看到的任何内容。这是来自我的产品选项的 graphQL 查询根。\n产品列表。

\n
ProductConnection!\nfirst: Int\nReturns up to the first n elements from the list.\n\nafter: String\nReturns the elements that come after the specified cursor.\n\nlast: Int\nReturns up to the last n elements from the list.\n\nbefore: String\nReturns the elements that come before the specified cursor.\n\nreverse: Boolean = false\nReverse the order of the underlying list.\n\nsortKey: ProductSortKeys = ID\nSort the underlying list by the given key.\n\nquery: String\nSupported filter parameters:\n\nbarcode\ncreated_at\ndelivery_profile_id\nerror_feedback\ngift_card\ninventory_total\nis_price_reduced\nout_of_stock_somewhere\nprice\nproduct_type\npublishable_status\npublished_status\nsku\nstatus\ntag\ntitle\nupdated_at\nvendor\nSee the detailed search syntax for more information about using filters.\n\nsavedSearchId: ID\nID of an existing saved search. The search\xe2\x80\x99s query string is used as the query argument.\n
Run Code Online (Sandbox Code Playgroud)\n

dri*_*rip 5

无论是使用 StoreFront GraphQL 还是管理 GraphQL,您都无法通过单个 GraphQL 请求获取所有产品。

如果您的产品数量低于 250 个,您可以使用 发出请求first: 250,但如果您的产品数量超过 250 个,则需要使用 GraphQL 的游标分页发出递归请求。因此,如果您有 1000 个产品,您将需要发出 4 个请求(取决于您使用的 API,店面或管理 graphql api,因为它们是不同的)

目前,无法通过 Shopify 提供的任何 API 使用单个请求获取所有产品。

实现此目的的唯一方法是使用以下代码制作自定义模板:

[
{% paginate collection.products by 9999 %}
  {% for product in collection.products %}
    {{product | json}}{% unless forloop.last %},{% endunless %}
  {% endfor %}
{% endpagination %}
]
Run Code Online (Sandbox Code Playgroud)

称之为类似的东西collection.ajax.liquid

并使用视图参数向其发出获取请求:

fetch('/collections/all?view=ajax').then((response) => handle the response)
Run Code Online (Sandbox Code Playgroud)

请记住,您拥有的产品越多,对该页面的请求就越长。如果您有 1000 个产品,则该请求最多可能需要 10 秒。因此,对于大量产品来说,这也不是一个很好的解决方案。


至于总计数,有一个液体对象,{{ collection.all_products_count }}或者如果您正在做管理工作,请使用其余 api,因为有一种方法可以获取产品计数,但 graphql 中没有。