首页 > 解决方案 > 将 shopify_api 与 graphql 查询一起使用时,当 nil 时无法获得 productByHandle 查询的结果

问题描述

当产品为 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=nil> 的未定义方法 `productByHandle')

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

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

我也尝试过从字符串更改!(这是返回的非空类型)到字符串,但我收到此错误:GraphQL::Client::ValidationError (Nullability mismatch on variable $productHandle and argument handle (String / String!)) My variable for $ productHandle 确实是一个字符串,所以不确定为什么这也不起作用。

任何帮助,将不胜感激。

谢谢!

标签: rubygraphqlshopifyshopify-api

解决方案


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

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

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


推荐阅读