Class: Firstclasspostcodes::Client
Instance Attribute Summary collapse
Class Method Summary
collapse
Instance Method Summary
collapse
#get_lookup
#get_postcode
Methods included from Events
#emit, #events, #off, #on
Constructor Details
#initialize(config = Configuration.default) ⇒ Client
Returns a new instance of Client.
17
18
19
20
21
22
23
|
# File 'lib/firstclasspostcodes/client.rb', line 17
def initialize(config = Configuration.default)
@config = config
@user_agent = "Firstclasspostcodes/ruby@#{Firstclasspostcodes::VERSION}"
on("request") { |req| @config.logger.debug(req) if @config.debug }
on("response") { |req| @config.logger.debug(req) if @config.debug }
on("error") { |req| @config.logger.error(req) }
end
|
Instance Attribute Details
#config ⇒ Object
The Configuration object holding settings to be used in the API client.
11
12
13
|
# File 'lib/firstclasspostcodes/client.rb', line 11
def config
@config
end
|
#user_agent ⇒ Object
The User-agent for the library
14
15
16
|
# File 'lib/firstclasspostcodes/client.rb', line 14
def user_agent
@user_agent
end
|
Class Method Details
.default ⇒ Object
77
78
79
|
# File 'lib/firstclasspostcodes/client.rb', line 77
def self.default
@default ||= Client.new
end
|
Instance Method Details
#build_request_url(path) ⇒ Object
71
72
73
74
75
|
# File 'lib/firstclasspostcodes/client.rb', line 71
def build_request_url(path)
path = "/#{path}".gsub(%r{/+}, "/")
@config.base_url + path
end
|
#call_request(*args) ⇒ Object
49
50
51
52
53
54
55
|
# File 'lib/firstclasspostcodes/client.rb', line 49
def call_request(*args)
response = Typhoeus::Request.new(*args).run
return response if response.success?
raise handle_request_error(response)
end
|
#handle_request_error(response) ⇒ Object
57
58
59
60
61
62
63
64
65
66
67
68
69
|
# File 'lib/firstclasspostcodes/client.rb', line 57
def handle_request_error(response)
raise ResponseError.new("Connection timed out", "timeout") if response.timed_out?
raise ResponseError.new(response.return_message, "liberror") if response.code == 0
error = begin
JSON.parse(response.body, symbolize_names: true)
rescue JSON::ParserError
response.body
end
raise ResponseError.new(error, "network-error")
end
|
#request(opts) ⇒ Object
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
|
# File 'lib/firstclasspostcodes/client.rb', line 25
def request(opts)
url = build_request_url(opts[:path])
request_params = {
params: opts[:query_params] || {},
method: opts[:method].to_sym.downcase,
}
request_params.merge!(@config.to_request_params)
emit("request", request_params)
response = call_request(url, request_params)
data = JSON.parse(response.body, symbolize_names: true)
emit("response", data)
data
rescue ResponseError => e
emit("error", e)
raise e
end
|