class ShopifyDump::Dumper

Constants

API_KEY
API_VERSION
PASSWORD
SHOP_NAME

Public Class Methods

new() click to toggle source
# File lib/shopify_dump/dumper.rb, line 13
def initialize
  ShopifyAPI::Base.site = "https://#{API_KEY}:#{PASSWORD}@#{SHOP_NAME}.myshopify.com"
  ShopifyAPI::Base.api_version = API_VERSION
  @client = ShopifyAPI::GraphQL.client
  @logger = Logger.new(STDOUT)
end

Public Instance Methods

dump(query, file_suffix = "") click to toggle source
# File lib/shopify_dump/dumper.rb, line 20
def dump(query, file_suffix = "")
  # start bulk operation
  start_bulk_operation(query)
  # download jsonl file
  download_jsonl(fetch_download_url, file_suffix)
end

Private Instance Methods

current_bulk_operation() click to toggle source
# File lib/shopify_dump/dumper.rb, line 68
  def current_bulk_operation
    @client.query(
      @client.parse(<<-'GRAPHQL')
        {
          currentBulkOperation {
            id
            status
            errorCode
            createdAt
            completedAt
            objectCount
            fileSize
            url
            partialDataUrl
          }
        }
      GRAPHQL
    )
  end
download_jsonl(url, file_suffix) click to toggle source
# File lib/shopify_dump/dumper.rb, line 88
def download_jsonl(url, file_suffix)
  open("shopify_#{file_suffix}.jsonl", "w") do |io|
    res = Net::HTTP.get_response(URI(url))
    io.write(res.body) if res.is_a?(Net::HTTPSuccess)
  end
end
fetch_download_url() click to toggle source
# File lib/shopify_dump/dumper.rb, line 52
def fetch_download_url
  i = 0
  while result = current_bulk_operation
    if result.to_h["data"]["currentBulkOperation"]["status"] == "COMPLETED"
      return result.to_h["data"]["currentBulkOperation"]["url"]
    elsif result.to_h["data"]["currentBulkOperation"]["status"] == "RUNNING"
      i += 10
      sleep(i)
    else
      @logger.warn("Bulk operation not running. " \
                   "Result:#{result.to_h["data"]["currentBulkOperation"]}")
      break
    end
  end
end
start_bulk_operation(query) click to toggle source
# File lib/shopify_dump/dumper.rb, line 29
  def start_bulk_operation(query)
    @client.query(
      @client.parse(<<~"GRAPHQL")
        mutation {
          bulkOperationRunQuery(
            query:"""
            #{query}
            """
          ) {
            bulkOperation {
              id
              status
            }
            userErrors {
              field
              message
            }
          }
        }
      GRAPHQL
    )
  end