将 Graphql 用于 Shopify 时的动态常量分配 API

Dynamic constant assignment when using Graphql for Shopify API

我在 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

我试过创建类似于上述 post 的客户端,就像这两个选项一样,但没有成功:

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

任何人都能够 运行 graphql 查询变量,在 Ruby 中并且没有得到这个错误?

这是解决方案。很难相信这是一种通过 API 访问数据的 "new" 方式。它更慢,更复杂,也更冗长。我完全没有得到好处。

  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

您可以通过这种方式避免使用常量:

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