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'
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With