GraphQL::Client::DynamicQueryError 预期定义分配给静态常量

ald*_*n.h 6 ruby ruby-on-rails graphql shopify-app

如何在 Rails 中制作正确的ShopifyAPI::GraphQL方法。

尝试下面的代码rails console工作正常。但是当我尝试将该代码放入 Rails 控制器/模型中并创建一个方法时,我得到:

GraphQL::Client::DynamicQueryError Expected definition to be assigned to a static constant

shopify_client
client = ShopifyAPI::GraphQL.new

SHOP_NAME_QUERY = client.parse <<-'GRAPHQL'
 {
  shop {
   name
  }
 }
GRAPHQL

result = client.query(SHOP_NAME_QUERY)
Run Code Online (Sandbox Code Playgroud)

我试图玩弄variables 以下https://github.com/github/graphql-client/blob/master/guides/dynamic-query-error.md 但没有成功

如何使用上述函数创建一个不会返回上述错误的方法。

示例模型方法

def trial
  shopify_client
  client = ShopifyAPI::GraphQL.new
  shop_query = client.parse <<-'GRAPHQL'
    {
     shop {
      name
     }
    }
  GRAPHQL

  client.query(shop_query)
end
Run Code Online (Sandbox Code Playgroud)

Gemfile 中gem 'shopify_api', git: 'https://github.com/Shopify/shopify_api', branch: 'graphql-support'

the*_*guy 6

几天前我遇到了类似的问题,我不得不使用const_set动态设置常量。因此,使用您的示例将转换为

class Foo
  def trial
   #code to initialize shopify session here 
   set_query
   client.query(ProductQuery)
  end

  private 

  def set_query 
     query = <<-GRAPHQL
        {
          shop {
          name
        }
      }
    GRAPHQL
    Kernel.const_set(:ProductQuery, client.parse(query))
  end

  def client
    ShopifyAPI::GraphQL.new
  end
end
Run Code Online (Sandbox Code Playgroud)

Shopify 的 GraphQL 功能依赖于Github GraphQL ruby​​ 客户端,它要求在常量中定义查询。此外,shopify_api gem在您可以使用此方法之前,要求存在 Shopify 会话,根据您的设置,如果常量位于类主体上,则您可能没有定义会话,因为它首先由 ruby​​ 解释器执行。解决这个问题的方法是动态设置常量


dra*_*vic 1

如果您使用以下内容,它是否有效:

class MyModel
  ShopQuery = ShopifyAPI::GraphQL.new.parse <<-'GRAPHQL'
  {
    shop {
      name
      }
  }
  GRAPHQL

  # ....
  def trial
    shopify_client

    ShopifyAPI::GraphQL.new.query(ShopQuery)
  end

end
Run Code Online (Sandbox Code Playgroud)

注意: shop_query -> ShopQuery因为你需要使用常量。