forked from alexreisner/geocoder
/
postcode_anywhere_uk.rb
51 lines (42 loc) · 1.59 KB
/
postcode_anywhere_uk.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
require 'geocoder/lookups/base'
require 'geocoder/results/postcode_anywhere_uk'
module Geocoder::Lookup
class PostcodeAnywhereUk < Base
# API documentation: http://www.postcodeanywhere.co.uk/Support/WebService/Geocoding/UK/Geocode/2/
BASE_URL_GEOCODE_V2_00 = 'services.postcodeanywhere.co.uk/Geocoding/UK/Geocode/v2.00/json.ws'
DAILY_LIMIT_EXEEDED_ERROR_CODES = ['8', '17'] # api docs say these two codes are the same error
INVALID_API_KEY_ERROR_CODE = '2'
def name
'PostcodeAnywhereUk'
end
def required_api_key_parts
%w(key)
end
def query_url(query)
format('%s://%s?%s', protocol, BASE_URL_GEOCODE_V2_00, url_query_string(query))
end
private
def results(query)
response = fetch_data(query)
return [] if response.nil? || !response.is_a?(Array) || response.empty?
raise_exception_for_response(response[0]) if response[0]['Error']
response
end
def raise_exception_for_response(response)
case response['Error']
when *DAILY_LIMIT_EXEEDED_ERROR_CODES
raise_error(Geocoder::OverQueryLimitError, response['Cause']) || warn(response['Cause'])
when INVALID_API_KEY_ERROR_CODE
raise_error(Geocoder::InvalidApiKey, response['Cause']) || warn(response['Cause'])
else # anything else just raise general error with the api cause
raise_error(Geocoder::Error, response['Cause']) || warn(response['Cause'])
end
end
def query_url_params(query)
{
:location => query.sanitized_text,
:key => configuration.api_key
}.merge(super)
end
end
end