Class: ShopifyAPI::GraphQL::Bulk::Create

Inherits:
Request
  • Object
show all
Defined in:
lib/shopify_api/graphql/bulk/create.rb

Overview

:nodoc:

Constant Summary collapse

FILENAME =
"bulk_import.jsonl"
STAGED_UPLOADS_CREATE =
<<~GQL
  mutation stagedUploadsCreate($input: [StagedUploadInput!]!) {
    stagedUploadsCreate(input: $input) {
      stagedTargets {
        url
        resourceUrl
        parameters {
          name
          value
        }
      }
      userErrors {
        field
        message
      }
    }
  }
GQL
BULK_OPERATION_RUN_MUTATION =
<<~GQL
  #{BULK_OPERATION_FIELDS}
  mutation bulkOperationRunMutation($mutation: String!, $stagedUploadPath: String!) {
    bulkOperationRunMutation(mutation: $mutation, stagedUploadPath: $stagedUploadPath) {
      bulkOperation {
        ...BulkOperationFields
      }
      userErrors {
        field
        message
      }
    }
  }
GQL

Instance Method Summary collapse

Constructor Details

#initialize(shop, token, options = nil) ⇒ Create

Returns a new instance of Create.



49
50
51
52
53
54
55
# File 'lib/shopify_api/graphql/bulk/create.rb', line 49

def initialize(shop, token, options = nil)
  super

  @shop = shop
  @token = token
  @file = Tempfile.new([self.class.name, ".jsonl"])
end

Instance Method Details

#<<(data) ⇒ Object



94
95
96
97
# File 'lib/shopify_api/graphql/bulk/create.rb', line 94

def <<(data)
  @file.puts(JSON.generate(data))
  nil
end

#execute(mutation, data = nil) {|_self| ... } ⇒ Object

Yields:

  • (_self)

Yield Parameters:

Raises:

  • (ArgumentError)


57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
# File 'lib/shopify_api/graphql/bulk/create.rb', line 57

def execute(mutation, data = nil)
  @file.truncate(0)
  @file.rewind

  @mutation = mutation

  Array(data).map { |d| self << d } if data
  yield self if block_given?

  @file.flush
  raise ArgumentError, "no data proviced to upload" if @file.size == 0

  input = [
    :resource => "BULK_MUTATION_VARIABLES",
    :filename => FILENAME,
    :mime_type => "text/jsonl",
    :http_method => "POST",
    :file_size => @file.size.to_s
  ]

  begin
    target = super(STAGED_UPLOADS_CREATE, :input => input).dig(:data, :staged_uploads_create, :staged_targets, 0)
  rescue => e
    raise Error, "stage upload request failed: #{e.message}"
  end

  upload_jsonl(target)
  upload_path = target[:parameters].find { |p| p[:name] == :key }

  begin
    data = super(BULK_OPERATION_RUN_MUTATION, :mutation => @mutation, :staged_upload_path => upload_path)
    Operation.new(data.dig(:data, :bulk_operation_run_mutation, :bulk_operation))
  rescue => e
    raise Error, "bulk run mutation request failed: #{e.message}"
  end
end