limits.rb 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. module ShopifyAPI
  2. module Limits
  3. class LimitUnavailable < StandardError; end
  4. def self.included(klass)
  5. klass.send(:extend, ClassMethods)
  6. end
  7. module ClassMethods
  8. # Takes form <call count>/<bucket size>
  9. # See https://help.shopify.com/en/api/getting-started/api-call-limit
  10. # Eg: 2/40
  11. CREDIT_LIMIT_HEADER_PARAM = {
  12. shop: 'X-Shopify-Shop-Api-Call-Limit',
  13. }
  14. ##
  15. # How many more API calls can I make?
  16. # @return {Integer}
  17. #
  18. def credit_left
  19. credit_limit(:shop) - credit_used(:shop)
  20. end
  21. alias_method :available_calls, :credit_left
  22. ##
  23. # Have I reached my API call limit?
  24. # @return {Boolean}
  25. #
  26. def credit_maxed?
  27. credit_left <= 0
  28. end
  29. alias_method :maxed?, :credit_maxed?
  30. ##
  31. # How many total API calls can I make?
  32. # NOTE: subtracting 1 from credit_limit because I think ShopifyAPI cuts off at 299 or shop limits.
  33. # @param {Symbol} scope [:shop]
  34. # @return {Integer}
  35. #
  36. def credit_limit(scope=:shop)
  37. api_credit_limit_param(scope).pop.to_i - 1
  38. end
  39. alias_method :call_limit, :credit_limit
  40. ##
  41. # How many API calls have I made?
  42. # @param {Symbol} scope [:shop]
  43. # @return {Integer}
  44. #
  45. def credit_used(scope=:shop)
  46. api_credit_limit_param(scope).shift.to_i
  47. end
  48. alias_method :call_count, :credit_used
  49. ##
  50. # @return {HTTPResonse}
  51. #
  52. def response
  53. Shop.current unless ShopifyAPI::Base.connection.response
  54. ShopifyAPI::Base.connection.response
  55. end
  56. private
  57. ##
  58. # @return {Array}
  59. #
  60. def api_credit_limit_param(scope)
  61. header = response[CREDIT_LIMIT_HEADER_PARAM[scope]]
  62. raise LimitUnavailable unless header
  63. header.split('/')
  64. end
  65. end
  66. end
  67. end