[Rails] Saving GraphQL Query to local database

Bryan_Beshore
New Member
9 0 0

Question

How can I store a GraphQL query in my local database?

- Is this something that I can create right in my model? How to map the fields? 

 

Sorry, I am a bit lost at the moment with this as it is all really new. 

Thanks!

Background

- Using rails shopify_app (shopify_api) gems

- Successfully setup webhooks to store new orders created in shopify in my database

- I am new to GraphQL

- I have a query set up in a shop.rb (model) that fetches data:

 

class Shop < ActiveRecord::Base
  include ShopifyApp::ShopSessionStorage

  def api_version
    ShopifyApp.configuration.api_version
  end

  session = ShopifyAPI::Session.new(domain: "bryanbeshore.myshopify.com", token: Shop.first.shopify_token, api_version: "2020-04")
  ShopifyAPI::Base.activate_session(session)

  client = ShopifyAPI::GraphQL.client

  SHOP_NAME_QUERY = client.parse <<-'GRAPHQL'
      {
    shop {
      name
    }
    orders(first: 100) {
      edges {
        node {
          id
          name
          createdAt
          shippingAddress {
            address1
            address2
            city
            province
            provinceCode
            zip
          }
        }
      }
    }
    }
  GRAPHQL
end

 

0 Likes
Bryan_Beshore
New Member
9 0 0

Ok. This was a dumb question and was thinking about GraphQL in a way I shouldn't have.

 

If anyone else has this issue, a quick/easy route for this would be to:

 

Create model - we'll call it saved_query with a name:string query:text 

 

You can then just use something like the below to get it in your database:

 

result = client.query(SHOP_NAME_QUERY)
result_json = result.data.to_json
SavedQuery.create(name: "SHOP NAME QUERY", query: result_json)

 

Probably not the way to do it in production, and simply storing this data every time the app loads is overkill, but again, just a way to do it...

0 Likes