【问题标题】:Dynamic constant assignment when using Graphql for Shopify API [duplicate]将 Graphql 用于 Shopify API 时的动态常量分配 [重复]
【发布时间】:2020-03-01 23:39:43
【问题描述】:

我在 Shopify API 上使用 Graphql,并且还需要在我的查询中使用变量。 I found this post, but it didn't work because I am using those query variables.

这是我得到的确切错误:

SyntaxError (/home/fc-gui/app/controllers/concerns/product_graphql.rb:26: dynamic constant assignment
FIRST_PRODUCTS = CLIENT.parse <<-'GRAPHQL'

然后这是我尝试运行查询的方法

  def run_first_query
    FIRST_PRODUCTS = CLIENT.parse <<-'GRAPHQL'
    query($first: Int){
      products(first: $first) {
        pageInfo {
          hasNextPage
        }
        edges {
          cursor
          node {
            id
            title
            featuredImage {
              originalSrc
            }
          }
        }
      }
    }
    GRAPHQL
    first = { "first": number_of_products_to_return}
    @query_result = CLIENT.query(FIRST_PRODUCTS, variables: first)
    get_last_cursor
  end

我已经尝试创建类似于上述帖子的客户端,就像这两个选项一样,但没有运气:

CLIENT = ShopifyAPI::GraphQL.new
##
def graphql_client
  ShopifyAPI::GraphQL.new
end

任何人都能够在 Ruby 中使用变量运行 graphql 查询并且不会出现此错误?

【问题讨论】:

  • 您尝试写入方法体内的常量 FIRST_PRODUCTS 不是问题吗?您可以尝试使用方法变量吗?

标签: ruby-on-rails ruby graphql shopify


【解决方案1】:

这是解决方案。很难相信这是一种通过 API 访问数据的“新”方式。它更慢,更复杂,更冗长。我根本没有得到好处。

  def run_first_query
    query = <<-'GRAPHQL'
    query($first: Int){
      products(first: $first) {
        pageInfo {
          hasNextPage
        }
        edges {
          cursor
          node {
            id
            title
            featuredImage {
              originalSrc
            }
          }
        }
      }
    }
    GRAPHQL
    first = { 
      "first": number_of_products_to_return,
    }
    Kernel.const_set(:ProductQuery, graphql_client.parse(query))
    @query_result = graphql_client.query(ProductQuery, variables: first)
  end

【讨论】:

    【解决方案2】:

    你可以避免使用这种风格的常量:

    query = ShopifyAPI::GraphQL.client.parse <<-'GRAPHQL'
      {
        shop {
          name
        }
      }
    GRAPHQL
    
    result = ShopifyAPI::GraphQL.client.query(query)
    puts "Shop name: #{result.data.shop.name}"
    

    我没有设置您的确切查询,但这解决了我正在查询的问题。

    来自他们的文档的参考:https://github.com/Shopify/shopify_api/blob/master/docs/graphql.md

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-03-21
      • 2017-04-08
      • 1970-01-01
      相关资源
      最近更新 更多