问题
How to make proper ShopifyAPI::GraphQL method in 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 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)
I tried to play around with variables
following https://github.com/github/graphql-client/blob/master/guides/dynamic-query-error.md
but no success.
How to make a method using the above function that will not return the mentioned error above.
Sample Model method:
def trial
shopify_client
client = ShopifyAPI::GraphQL.new
shop_query = client.parse <<-'GRAPHQL'
{
shop {
name
}
}
GRAPHQL
client.query(shop_query)
end
In Gemfile: gem 'shopify_api', git: 'https://github.com/Shopify/shopify_api', branch: 'graphql-support'
回答1:
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'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
回答2:
Finally got one working.
# On top of my Rails Controller || Model
SHOPIFY_CLIENT = shopify_client # (hash data e.g. {"User-Agent"=>"xxx", "X-Shopify-Access-Token"=>"xxx"})
CLIENT = ShopifyAPI::GraphQL.new
SHOP_NAME_QUERY = CLIENT.parse <<-'GRAPHQL'
{
shop{
name
}
}
GRAPHQL
# ex. method
def get_info
CLIENT.query(SHOP_NAME_QUERY).data
end
I can now continue working with other requests... Hope this help someone :)
回答3:
Does it work if you use:
class MyModel
ShopQuery = ShopifyAPI::GraphQL.new.parse <<-'GRAPHQL'
{
shop {
name
}
}
GRAPHQL
# ....
def trial
shopify_client
ShopifyAPI::GraphQL.new.query(ShopQuery)
end
end
Note: shop_query -> ShopQuery
because you need to use constant.
来源:https://stackoverflow.com/questions/50382830/graphqlclientdynamicqueryerror-expected-definition-to-be-assigned-to-a-stati