【问题标题】:Unable to get result of productByHandle query when nil when using shopify_api with graphql query将 shopify_api 与 graphql 查询一起使用时,当 nil 时无法获得 productByHandle 查询的结果
【发布时间】:2021-09-30 19:26:42
【问题描述】:

当产品为 nil 时,我尝试使用 productByHandle 查询从 graphQL 查询中检索结果,但它出错了。

我的 Ruby 代码:

client = ShopifyAPI::GraphQL.client
 product_handle_query = client.parse <<-'GRAPHQL'
  query ($productHandle: String!) {
   productByHandle(handle: $productHandle) {
     id
     handle
     title
     tags
     productType
     vendor
   }
 }
 GRAPHQL
result = client.query(product_handle_query, variables: {productHandle: productHandle})
puts result.data.productByHandle

这应该返回 nil,但是当我尝试发送消息时,它会返回以下错误:

NoMethodError(# 的未定义方法 `productByHandle')

此查询在 Insomnia 中运行良好,输出如下所示:

{
"data": {
"productByHandle": null
},
"extensions": {
"cost": {
"requestedQueryCost": 1,
"actualQueryCost": 1,
"throttleStatus": {
"maximumAvailable": 2000.0,
"currentlyAvailable": 1999,
"restoreRate": 100.0
}
}
}
}

我也尝试过从字符串更改! (这是返回的非空类型)到String,但我收到此错误: GraphQL::Client::ValidationError(变量 $productHandle 和参数句柄(字符串/字符串!)的可空性不匹配) 我的 $productHandle 变量确实是一个字符串,所以不知道为什么这也不起作用。

任何帮助将不胜感激。

谢谢!

【问题讨论】:

  • 索要产品并提供 nil 是什么意思?只是好奇一个用例。
  • 我正在根据产品句柄查询产品,它返回 nil,因为该产品尚不存在。 @大卫拉扎
  • 如何处理不存在的东西?如果你没有把手,你为什么要问什么都不存在?存在的!
  • 这是这个查询的重点,在创建产品之前查看产品是否存在。我不想在我的商店中出现重复的产品。 @大卫拉扎
  • 最简单的方法是处理您希望使用的标题,然后将其用作您要调用的句柄。如果它已经存在,你会取回一个产品,否则为零。但当然你也可以通过其他方式做到这一点。不确定这是否重要。

标签: ruby graphql shopify shopify-api


【解决方案1】:

弄清楚如何从上面的输出中读取结果:

result.original_hash["data"]["productByHandle"] 

这将返回 nil 并允许我继续创建新产品。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-05-08
    • 2021-12-12
    • 1970-01-01
    • 2020-06-11
    • 1970-01-01
    • 2021-05-08
    • 1970-01-01
    相关资源
    最近更新 更多