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'
3
Answers
Finally got a simple one working.
I can now continue working with other requests... Hope this help someone :)
Does it work if you use:
Note:
shop_query -> ShopQuery
because you need to use constant.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 toShopify’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