GraphQL::Client::DynamicQueryError 预期将定义分配给静态常量 [英] GraphQL::Client::DynamicQueryError Expected definition to be assigned to a static constant

查看:15
本文介绍了GraphQL::Client::DynamicQueryError 预期将定义分配给静态常量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在 Rails 中创建正确的 ShopifyAPI::GraphQL 方法.

How to make proper ShopifyAPI::GraphQL method in Rails.

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

Trying the below code in rails console works fine. But when I tried to put that code and make a method in Rails controller/model, i'm getting:

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

shopify_client
client = ShopifyAPI::GraphQL.new

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

result = client.query(SHOP_NAME_QUERY)

我尝试使用变量按照 https://github.com/github/graphql-client/blob/master/guides/dynamic-query-error.md 但没有成功.

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

How to make a method using the above function that will not return the mentioned error above.

样本模型方法:

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

  client.query(shop_query)
end

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

推荐答案

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

I had a similar issue a few days ago, I had to use const_set for setting the constant dynamically. So, using your example that would translate to

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

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

Shopify's GraphQL feature relies on the Github GraphQL ruby client, which mandates query be defined in a constant. Also, the shopify_api gem mandates the existence of a Shopify session before you can use this method, depending on your setup you may not have a session defined if the constant is on the class body as that get executed first by the ruby interpreter. The way around this is to set the constant dynamically

这篇关于GraphQL::Client::DynamicQueryError 预期将定义分配给静态常量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆