skip to Main Content

I am using Graphql on the Shopify API and also needing to use variables in my query. I found this post, but it didn’t work because I am using those query variables.

This is the exact error I’m getting:

SyntaxError (/home/fc-gui/app/controllers/concerns/product_graphql.rb:26: dynamic constant assignment
FIRST_PRODUCTS = CLIENT.parse <<-'GRAPHQL'

And then here is the method where I’m trying to run my query

  def run_first_query
    FIRST_PRODUCTS = CLIENT.parse <<-'GRAPHQL'
    query($first: Int){
      products(first: $first) {
        pageInfo {
          hasNextPage
        }
        edges {
          cursor
          node {
            id
            title
            featuredImage {
              originalSrc
            }
          }
        }
      }
    }
    GRAPHQL
    first = { "first": number_of_products_to_return}
    @query_result = CLIENT.query(FIRST_PRODUCTS, variables: first)
    get_last_cursor
  end

I’ve tried creating the client similar to the aforementioned post, like these two options, but no luck:

CLIENT = ShopifyAPI::GraphQL.new
##
def graphql_client
  ShopifyAPI::GraphQL.new
end

Anyone able to run graphql queries with variables, in Ruby and NOT get this error?

2

Answers


  1. Chosen as BEST ANSWER

    And here is the solution. Super hard to believe this is a "new" way of accessing data via an API. Its slower, more complicated and much more verbose. I don't get the benefit at all.

      def run_first_query
        query = <<-'GRAPHQL'
        query($first: Int){
          products(first: $first) {
            pageInfo {
              hasNextPage
            }
            edges {
              cursor
              node {
                id
                title
                featuredImage {
                  originalSrc
                }
              }
            }
          }
        }
        GRAPHQL
        first = { 
          "first": number_of_products_to_return,
        }
        Kernel.const_set(:ProductQuery, graphql_client.parse(query))
        @query_result = graphql_client.query(ProductQuery, variables: first)
      end
    

  2. You can avoid using constants using this style:

    query = ShopifyAPI::GraphQL.client.parse <<-'GRAPHQL'
      {
        shop {
          name
        }
      }
    GRAPHQL
    
    result = ShopifyAPI::GraphQL.client.query(query)
    puts "Shop name: #{result.data.shop.name}"
    

    I didn’t set up your exact query but this solved the problem for the queries I was making.

    Reference from their docs: https://github.com/Shopify/shopify_api/blob/master/docs/graphql.md

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search