Skip to content

Instantly share code, notes, and snippets.

@sshaw
Last active May 9, 2021 00:31
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save sshaw/6043fa838e1cecf9d902 to your computer and use it in GitHub Desktop.
Save sshaw/6043fa838e1cecf9d902 to your computer and use it in GitHub Desktop.
Ruby module to retry a Shopify API request if an HTTP 429 (too many requests) is returned. Moved to https://github.com/ScreenStaring/shopify_api_retry with GraphQL support
require "shopify_api"
#
# Retry a ShopifyAPI request if an HTTP 429 (too many requests) is returned.
#
# ShopifyAPIRetry.retry { customer.update_attribute(:tags, "foo") }
# ShopifyAPIRetry.retry(30) { customer.update_attribute(:tags, "foo") }
# c = ShopifyAPIRetry.retry { ShopifyAPI::Customer.find(id) }
#
# By Skye Shaw (https://gist.github.com/sshaw/6043fa838e1cecf9d902)
module ShopifyAPIRetry
VERSION = "0.0.1".freeze
HTTP_RETRY_AFTER = "Retry-After".freeze
def retry(seconds_to_wait = nil)
raise ArgumentError, "block required" unless block_given?
raise ArgumentError, "seconds to wait must be > 0" unless seconds_to_wait.nil? || seconds_to_wait > 0 # maybe enforce 2?
result = nil
retried = false
begin
result = yield
rescue ActiveResource::ClientError => e
# Not 100% if we need to check for code method, I think I saw a NoMethodError...
raise unless !retried && e.response.respond_to?(:code) && e.response.code.to_i == 429
seconds_to_wait = (e.response[HTTP_RETRY_AFTER] || 2).to_i unless seconds_to_wait
sleep seconds_to_wait
retried = true
retry
end
result
end
module_function :retry
end
@sshaw
Copy link
Author

sshaw commented Mar 3, 2016

@efrapp
Copy link

efrapp commented Sep 22, 2017

Hey man thanks for this module. It helped me a lot!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment