Class: NbApiClient::Request

Inherits:
Object
  • Object
show all
Defined in:
lib/nb_api_client/request.rb

Overview

Makes an authenticated request against the NationBuilder API on behalf of a "nation" (any object satisfying the interface documented in the gem README), handling rate limiting, OAuth token refresh, and repeated-authorization-failure deauthorization.

Defined Under Namespace

Classes: InvalidContentType, RateLimitedError, UnauthorizedNationError

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(nation, action, path, body = {}) ⇒ Request

Returns a new instance of Request.



37
38
39
40
41
42
43
# File 'lib/nb_api_client/request.rb', line 37

def initialize(nation, action, path, body = {})
  @nation = nation
  @action = action
  @path = path
  @url = UrlBuilder.new(@nation, @path).url
  @body = body.is_a?(Hash) ? body.to_json : body
end

Class Method Details

.callObject



33
34
35
# File 'lib/nb_api_client/request.rb', line 33

def self.call(...)
  new(...).call
end

Instance Method Details

#callObject



45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
# File 'lib/nb_api_client/request.rb', line 45

def call
  config = NbApiClient.configuration
  return {} if config.short_circuit_in_test && defined?(Rails) && Rails.respond_to?(:env) && Rails.env.test?
  raise UnauthorizedNationError.new(nation: @nation.slug) unless @nation.active? || @path == "/oauth/token"

  options = {timeout: 30, uri_adapter: Addressable::URI}
  rate_limit_retries = 0
  token_retries = 0

  loop do
    @response = RateLimiter.with_limit do
      HTTParty.send(
        @action,
        @url,
        body: @body,
        headers: {Accept: "application/json", "Content-type": "application/json"},
        **options
      )
    end

    return @response if @response.success?

    if rate_limit_error?
      wait_seconds = @response.headers["retry-after"].to_i + 1
      config.logger&.warn("[NbApiClient::Request] Rate limited: #{@action.upcase} #{@path} nation=#{@nation.slug} retry_after=#{wait_seconds}s rate_limit_retries=#{rate_limit_retries}")

      raise RateLimitedError.new(retry_after: wait_seconds) if (rate_limit_retries += 1) > config.max_rate_limit_retries

      sleep wait_seconds
      next
    elsif expired_token_error?
      raise OAuth2::Error.new(@response) if (token_retries += 1) > config.max_token_retries
      raise OAuth2::Error.new(@response) unless @nation.refresh_oauth_token

      next
    elsif unauthorized_error?
      raise OAuth2::Error.new(@response) if (token_retries += 1) > config.max_token_retries

      if too_many_unauthorized_errors?(config)
        @nation.deauthorize
        config.on_repeated_unauthorized&.call(@nation)
        raise UnauthorizedNationError.new(nation: @nation.slug)
      end

      @nation.refresh_oauth_token
      next
    elsif @response.content_type.in?(["application/json", "application/vnd.api+json"])
      raise OAuth2::Error.new(@response)
    else
      raise InvalidContentType.new(nation: @nation.slug, body: @response.body, content_type: @response.content_type)
    end
  end
end