-
-
Save shopifypartners/bd0f05bb176602da7fcecf8814bd4854 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 |
I'd love to see it to :)
There must be some extra way to add credits, otherwise the lock will block infinitely
This code was clearly not tested or executed even once.
shame.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
What's inside the obtain_credit?