Last active
May 9, 2021 00:31
-
-
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
This file contains 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
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 |
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
Also see shopify-api-throttle.