limits.rb 2.0 KB

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