collection_pagination.rb 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. module ShopifyAPI
  2. module CollectionPagination
  3. def initialize(args)
  4. @previous_url_params = extract_url_params(pagination_link_headers.previous_link)
  5. @next_url_params = extract_url_params(pagination_link_headers.next_link)
  6. super(args)
  7. end
  8. def next_page?
  9. ensure_available
  10. @next_url_params.present?
  11. end
  12. def previous_page?
  13. ensure_available
  14. @previous_url_params.present?
  15. end
  16. def fetch_next_page
  17. fetch_page(@next_url_params)
  18. end
  19. def fetch_previous_page
  20. fetch_page(@previous_url_params)
  21. end
  22. private
  23. AVAILABLE_IN_VERSION = ShopifyAPI::ApiVersion::Unstable.new
  24. def fetch_page(url_params)
  25. ensure_available
  26. return [] unless url_params.present?
  27. resource_class.where(url_params)
  28. end
  29. def extract_url_params(link_header)
  30. return nil unless link_header.present?
  31. Rack::Utils.parse_nested_query(link_header.url.query)
  32. end
  33. def pagination_link_headers
  34. @pagination_link_headers ||= ShopifyAPI::PaginationLinkHeaders.new(
  35. ShopifyAPI::Base.connection.response["Link"]
  36. )
  37. end
  38. def ensure_available
  39. raise NotImplementedError unless ShopifyAPI::Base.api_version >= AVAILABLE_IN_VERSION
  40. end
  41. end
  42. end