55require 'messagebird/balance'
66require 'messagebird/error'
77require 'messagebird/hlr'
8+ require 'messagebird/http_client'
89require 'messagebird/verify'
910require 'messagebird/message'
1011require 'messagebird/voicemessage'
@@ -19,42 +20,19 @@ def initialize(errors)
1920 end
2021 end
2122
22- class InvalidPhoneNumberException < TypeError ; end
23-
2423 class Client
24+
2525 attr_reader :access_key
26+ attr_reader :http_client
2627
27- def initialize ( access_key = nil )
28+ def initialize ( access_key = nil , http_client = nil )
2829 @access_key = access_key || ENV [ 'MESSAGEBIRD_ACCESS_KEY' ]
30+ @http_client = http_client || HttpClient . new ( @access_key )
2931 end
3032
3133 def request ( method , path , params = { } )
32- uri = URI . join ( ENDPOINT , '/' , path )
33-
34- # Set up the HTTP object.
35- http = Net ::HTTP . new ( uri . host , uri . port )
36- http . use_ssl = true
37-
38- # Construct the HTTP GET or POST request.
39- request = Net ::HTTP ::Get . new ( uri . request_uri ) if method == :get
40- request = Net ::HTTP ::Post . new ( uri . request_uri ) if method == :post
41- request [ 'Accept' ] = 'application/json'
42- request [ 'Authorization' ] = "AccessKey #{ @access_key } "
43- request [ 'User-Agent' ] = "MessageBird/ApiClient/#{ CLIENT_VERSION } Ruby/#{ RUBY_VERSION } "
44-
45- # If present, add the HTTP POST parameters.
46- request . set_form_data ( params ) if method == :post && !params . empty?
47-
48- # Execute the request and fetch the response.
49- response = http . request ( request )
50-
51- # Parse the HTTP response.
52- case response . code . to_i
53- when 200 , 201 , 204 , 401 , 404 , 405 , 422
54- json = JSON . parse ( response . body )
55- else
56- raise InvalidPhoneNumberException , 'Unknown response from server'
57- end
34+ response_body = @http_client . request ( method , path , params )
35+ json = JSON . parse ( response_body )
5836
5937 # If the request returned errors, create Error objects and raise.
6038 if json . has_key? ( 'errors' )
0 commit comments