class Lucid::Shopify::BulkRequest

Constants

CanceledOperationError
ExpiredOperationError
FailedOperationError
ObsoleteOperationError
OperationError
TimeoutError

Public Instance Methods

call(client, credentials, query) click to toggle source

Create and start a new bulk operation via the GraphQL API. Any currently running bulk operations are cancelled.

@param client [Client] @param credentials [Credentials] @param query [String] the GraphQL query

@return [Operation]

@example

bulk_request.(client, credentials, <<~QUERY).() do |products|
  {
    products {
      edges {
        node {
          id
          handle
        }
      }
    }
  }
QUERY
  db.transaction do
    products.each do |product|
      db[:products].insert(
        id: product['id'],
        handle: product['handle'],
      )
    end
  end
end
# File lib/lucid/shopify/bulk_request.rb, line 182
      def call(client, credentials, query)
        Shopify.assert_api_version!('2019-10')

        op = client.post_graphql(credentials, <<~QUERY)['data']['currentBulkOperation']
          {
            currentBulkOperation {
              id
              status
              url
            }
          }
        QUERY

        case op&.fetch('status')
        when 'CANCELING'
          Operation.new(client, credentials, op['id']).poll_until(['CANCELED'])
        when 'CREATED', 'RUNNING'
          Operation.new(client, credentials, op['id']).cancel
        end

        id = client.post_graphql(credentials, <<~QUERY)['data']['bulkOperationRunQuery']['bulkOperation']['id']
          mutation {
            bulkOperationRunQuery(
              query: """
                #{query}
              """
            ) {
              bulkOperation {
                id
              }
              userErrors {
                field
                message
              }
            }
          }
        QUERY

        Operation.new(client, credentials, id)
      end