Created
December 9, 2012 02:56
-
-
Save ianneub/4243115 to your computer and use it in GitHub Desktop.
Shopify API tweak to easily paginate API calls
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
ShopifyAPI::Customer.find_all do |customer| | |
# do something with the customer | |
end | |
ShopifyAPI::Order.find_all(:status => :any) do |order| | |
# do something with the order | |
end | |
ShopifyAPI::Product.find_all(:limit => 250) do |order| | |
# do something with the product | |
end |
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
# Big thank you to Scott Wheeler and BBG in the Shopify API Forums | |
# http://ecommerce.shopify.com/c/shopify-apis-and-technology/t/paginate-api-results-113066 | |
module ShopifyAPI | |
class Base | |
RETRY_AFTER = 60 | |
def self.find_all(params = {}, &block) | |
params[:limit] ||= 50 | |
params[:page] = 1 | |
retried = false | |
begin | |
until find(:all, :params => params).each { |value| block.call(value) }.length < params[:limit] | |
params[:page] += 1 | |
retried = false | |
end | |
rescue ActiveResource::ConnectionError, ActiveResource::ServerError, | |
ActiveResource::ClientError => ex | |
unless retried | |
sleep(((ex.respond_to?(:response) && ex.response['Retry-After']) || RETRY_AFTER).to_i) | |
retried = true | |
retry | |
else | |
raise ex | |
end | |
end | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment