Skip to content

Instantly share code, notes, and snippets.

@daniel-sim
Last active March 9, 2021 08:25
Show Gist options
  • Save daniel-sim/1805046f12282d594a687f20f320a27a to your computer and use it in GitHub Desktop.
Save daniel-sim/1805046f12282d594a687f20f320a27a to your computer and use it in GitHub Desktop.
class Transaction < ActiveRecord::Base
include ShopifyPartnerAPI
THROTTLE_MIN_TIME_PER_CALL = 0.3
TRANSACTIONS_QUERY = ShopifyPartnerAPI.client.parse <<-'GRAPHQL'
query($cursor: String) {
transactions(types: [APP_SUBSCRIPTION_SALE], after: $cursor, first: 100) {
edges {
cursor
node {
id,
createdAt,
... on AppSubscriptionSale {
netAmount {
amount
},
app {
name
},
shop {
myshopifyDomain
}
},
... on ServiceSale {
netAmount {
amount
},
shop {
myshopifyDomain
}
}
}
},
pageInfo {
hasNextPage
}
}
}
GRAPHQL
class << self
def import_transactions(partner_api_access_token, partner_api_organization_id)
cursor = ""
has_next_page = true
throttle_start_time = Time.zone.now
while has_next_page == true
throttle_start_time = throttle(throttle_start_time)
transactions = []
results = ShopifyPartnerAPI.client.query(
TRANSACTIONS_QUERY,
variables: {cursor: cursor},
context: {access_token: partner_api_access_token, organization_id: partner_api_organization_id}
)
raise StandardError.new(results.errors.messages.map { |k, v| "#{k}=#{v}" }.join("&")) if results.errors.any?
return if results.data.nil?
transactions = results.data.transactions.edges
has_next_page = results.data.transactions.page_info.has_next_page
cursor = results.data.transactions.edges.last.cursor
transactions.each do |transaction|
node = transaction.node
Transaction.new(node)
end
end
rescue => e
Rails.logger.info(e.message)
Rails.logger.info(e.backtrace.join("\n"))
Rails.logger.info(transactions.to_json) if transactions.present?
raise e
end
private
def throttle(start_time)
stop_time = Time.zone.now
processing_duration = stop_time - start_time
wait_time = (THROTTLE_MIN_TIME_PER_CALL - processing_duration).round(1)
Rails.logger.info("THROTTLING: #{wait_time}")
sleep wait_time if wait_time > 0.0
Time.zone.now
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment