Class: NationBuilder::Client

Inherits:
Object
  • Object
show all
Defined in:
lib/nationbuilder/client.rb

Defined Under Namespace

Classes: InvalidEndpoint

Constant Summary collapse

RETRY_DELAY =

seconds

0.1

Instance Method Summary collapse

Constructor Details

#initialize(nation_name, api_key, opts = {}) ⇒ Client

Returns a new instance of Client.



3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
# File 'lib/nationbuilder/client.rb', line 3

def initialize(nation_name, api_key, opts = {})
  @nation_name = nation_name
  @api_key = api_key
  @name_to_endpoint = {}
  @base_url = opts[:base_url] || 'https://:nation_name.nationbuilder.com'
  @retries = opts[:retries] || 8

  if @retries < 0
    raise 'Retries must be at least zero'
  end

  parsed_endpoints.each do |endpoint|
    @name_to_endpoint[endpoint.name] = endpoint
  end
end

Instance Method Details

#[](endpoint) ⇒ Object

Raises:



26
27
28
29
30
# File 'lib/nationbuilder/client.rb', line 26

def [](endpoint)
  e = @name_to_endpoint[endpoint]
  raise InvalidEndpoint.new(endpoint) if e.nil?
  e
end

#base_urlObject



36
37
38
# File 'lib/nationbuilder/client.rb', line 36

def base_url
  @base_url.gsub(':nation_name', @nation_name)
end

#call(endpoint_name, method_name, args = {}) ⇒ Object



68
69
70
71
72
73
74
75
# File 'lib/nationbuilder/client.rb', line 68

def call(endpoint_name, method_name, args={})
  endpoint = self[endpoint_name]
  method = endpoint[method_name]
  nonmethod_args = method.nonmethod_args(args)
  method_args = method.method_args(args)
  method.validate_args(method_args)
  return raw_call(method.uri, method.http_method, nonmethod_args, args)
end

#classify_response_error(response) ⇒ Object



106
107
108
109
110
111
112
113
114
115
# File 'lib/nationbuilder/client.rb', line 106

def classify_response_error(response)
  case
  when response.code == 429
    NationBuilder::RateLimitedError.new(response.body)
  when response.code.to_s.start_with?('4')
    NationBuilder::ClientError.new(response.body)
  when response.code.to_s.start_with?('5')
    NationBuilder::ServerError.new(response.body)
  end
end

#endpointsObject



32
33
34
# File 'lib/nationbuilder/client.rb', line 32

def endpoints
  @name_to_endpoint.keys
end

#parse_response_body(response) ⇒ Object



117
118
119
120
121
122
123
124
125
126
127
128
# File 'lib/nationbuilder/client.rb', line 117

def parse_response_body(response)
  error = classify_response_error(response)
  raise error if error

  if response.header['Content-Type'].first != 'application/json'
    return true
  end

  body = response.body.strip
  return {} if body.length == 0
  return JSON.parse(body)
end

#parsed_endpointsObject



19
20
21
22
# File 'lib/nationbuilder/client.rb', line 19

def parsed_endpoints
  NationBuilder::SpecParser
    .parse(File.join(File.dirname(__FILE__), 'api_spec.json'))
end

#perform_request_with_retries(method, url, request_args) ⇒ Object



77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
# File 'lib/nationbuilder/client.rb', line 77

def perform_request_with_retries(method, url, request_args)
  raw_response = HTTPClient.send(method, url, request_args)
  parsed_response = nil

  (@retries + 1).times do |i|
    begin
      parsed_response = parse_response_body(raw_response)
    rescue NationBuilder::RateLimitedError
      Kernel.sleep(RETRY_DELAY * 2**i)
    rescue => e
      raise e
    else
      break
    end
  end

  set_response(raw_response)
  parsed_response
end


130
131
132
133
134
135
# File 'lib/nationbuilder/client.rb', line 130

def print_all_descriptions
  endpoints.each do |endpoint_name|
    self.print_description(endpoint_name)
    puts
  end
end


137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
# File 'lib/nationbuilder/client.rb', line 137

def print_description(endpoint_name)
  endpoint_name = endpoint_name.to_sym

  unless self.endpoints.include?(endpoint_name)
    puts "Invalid endpoint name: #{endpoint_name}"
    puts
    puts "Valid endpoint names:"
    self.endpoints.each do |endpoint|
      puts "  #{endpoint}"
    end
    return
  end

  endpoint_str = "Endpoint: #{endpoint_name}"
  puts "=" * endpoint_str.length
  puts endpoint_str
  puts "=" * endpoint_str.length

  self[endpoint_name].methods.each do |method_name|
    puts
    method = self[endpoint_name][method_name]
    puts "  Method: #{method_name}"
    puts "  Description: #{method.description}"
    required_params = method.parameters.map { |p| p }
    if required_params.any?
      puts "  Required parameters: #{required_params.join(', ')}"
    end
  end
end

#raw_call(path, method, body = {}, args = {}) ⇒ Object



42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
# File 'lib/nationbuilder/client.rb', line 42

def raw_call(path, method, body = {}, args = {})
  url = NationBuilder::URL.new(base_url).generate_url(path, args)

  request_args = {
    header: {
      'Accept' => 'application/json',
      'Content-Type' => 'application/json'
    },
    query: {
      access_token: @api_key
    }
  }

  if method == :get
    request_args[:query].merge!(body)
  else
    body[:access_token] = @api_key
    if !body[:fire_webhooks].nil?
      request_args[:query][:fire_webhooks] = body[:fire_webhooks]
    end
    request_args[:body] = JSON(body)
  end

  perform_request_with_retries(method, url, request_args)
end

#responseObject

This getter is used for fetching the raw response



102
103
104
# File 'lib/nationbuilder/client.rb', line 102

def response
  Thread.current[:nationbuilder_rb_response]
end

#set_response(value) ⇒ Object



97
98
99
# File 'lib/nationbuilder/client.rb', line 97

def set_response(value)
  Thread.current[:nationbuilder_rb_response] = value
end