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

查看:50
本文介绍了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红宝石客户端,该命令要求在不变.另外,在使用此方法之前, shopify_api gem 要求存在Shopify会话,根据常量的设置,如果常量位于类主体上,则可能没有定义会话,因为该常量首先被执行由红宝石翻译.解决此问题的方法是动态设置常量

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天全站免登陆