Class: FederalRepLookup::WhoIsMyRepClient

Inherits:
Object
  • Object
show all
Defined in:
lib/federal_rep_lookup/who_is_my_rep_client.rb

Constant Summary collapse

BASE_URL =
"https://whoismyrepresentative.com/getall_mems.php"

Instance Method Summary collapse

Instance Method Details

#lookup(zipcode:) ⇒ Object



5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
# File 'lib/federal_rep_lookup/who_is_my_rep_client.rb', line 5

def lookup(zipcode:)
  encoded_params = URI.encode_www_form(
    zip: zipcode,
    output: :json,
  )
  url = [BASE_URL, '?', encoded_params].join
  response = Faraday.get(url)

  results = JSON.parse(response.body)['results']
  results.map do |result|
    CongressPerson.new(**result)
  end
rescue JSON::ParserError
  if response.body.match?(/message=['"]No Data Found['"]/)
    # When no congress people are found for a zipcode the service returns
    # an XML document. That cannot be parsed as JSON so we rescue the parse
    # error and return an empty array if the not found message appears.
    []
  else
    raise
  end
end