limits.rb 1.8 KB

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