Forked from shopifypartners/shopify-api-call-limit-with-mutex.rb
Created
January 12, 2019 10:32
-
-
Save raecoo/1c57bd52b404e1c1b676380c1abb7003 to your computer and use it in GitHub Desktop.
Shopify API Ruby example shared credits_remaining with Mutex - https://www.shopify.com/partners/blog/84051654-7-tips-to-maximize-your-use-of-the-shopify-api
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# use a shared lock and credits_remaining | |
@lock = Mutex.new | |
@credits_remaining = 40 | |
@shopify_url = ENV["SHOPIFY_URL"] | |
# Sends a request to Shopify, blocking until credits are available | |
def self.request(method, path, params={}) | |
params[:headers] = {"Content-Type" => "application/json"} | |
# wait for a credit | |
wait_for_credits | |
# send the request | |
response = Excon.new(File.join(@shopify_url, path), params).request(method: method) | |
# set the credits remaining from the response | |
set_credits_remaining_from_response(response) | |
JSON.parse(response.body) | |
end | |
# Wait for API credits to be available | |
def self.wait_for_credits | |
while !obtain_credit | |
puts "Waiting 10 seconds for a credit" | |
sleep(10) | |
end | |
end | |
# Set the current credits remaining from the response | |
# | |
# Returns used, total amounts | |
def self.set_credits_remaining_from_response(response) | |
used, total = parse_credit_limit_from_response(response) | |
@lock.synchronize do | |
@credits_remaining = total - used | |
puts "Setting credits from response - credits remaining: #{@credits_remaining}" | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment