1- require 'faraday'
2- require 'json'
3-
41module Deploy
52 class Request
63
@@ -23,41 +20,47 @@ def output
2320 ## Make a request to the Deploy API using net/http. Data passed can be a hash or a string
2421 ## Hashes will be converted to JSON before being sent to the remote service.
2522 def make
26- uri = URI . parse ( Deploy . configuration . account )
27- connection_url = "#{ uri . scheme } ://#{ uri . host } :#{ uri . port } "
23+ uri = URI . parse ( [ Deploy . configuration . account , @path ] . join ( '/' ) )
24+ http_request = http_class . new ( uri . request_uri )
25+ http_request . basic_auth ( Deploy . configuration . username , Deploy . configuration . api_key )
26+ http_request [ "Accept" ] = "application/json"
27+ http_request [ "Content-Type" ] = "application/json"
2828
29- connection = Faraday . new ( url : connection_url , request : { timeout : 3 } ) do |client |
30- client . request :authorization , :basic , Deploy . configuration . username , Deploy . configuration . api_key
31- client . headers [ 'Accept' ] = 'application/json'
32- client . headers [ 'Content-Type' ] = 'application/json'
29+ http = Net ::HTTP . new ( uri . host , uri . port )
30+ if uri . scheme == 'https'
31+ http . use_ssl = true
3332 end
3433
3534 data = self . data . to_json if self . data . is_a? ( Hash ) && self . data . respond_to? ( :to_json )
36-
37- response = connection . send ( @method ) do |req |
38- req . url @path
39- req . body = data
40- end
41-
42- @output = response . body
43- @success = case response . status
44- when 200 ..299
35+ http_result = http . request ( http_request , data )
36+ @output = http_result . body
37+ @success = case http_result
38+ when Net ::HTTPSuccess
4539 true
46- when 503
40+ when Net :: HTTPServiceUnavailable
4741 raise Deploy ::Errors ::ServiceUnavailable
48- when 401 , 403
42+ when Net :: HTTPForbidden , Net :: HTTPUnauthorized
4943 raise Deploy ::Errors ::AccessDenied , "Access Denied for '#{ Deploy . configuration . username } '"
50- when 404
44+ when Net :: HTTPNotFound
5145 raise Deploy ::Errors ::CommunicationError , "Not Found at #{ uri . to_s } "
52- when 400 .. 499
46+ when Net :: HTTPClientError
5347 false
5448 else
55- raise Deploy ::Errors ::CommunicationError , response . body
49+ raise Deploy ::Errors ::CommunicationError , http_result . body
5650 end
57-
5851 self
59- rescue Faraday ::TimeoutError
60- raise Deploy ::Errors ::TimeoutError , "Your request timed out, please try again in a few seconds"
52+ end
53+
54+ private
55+
56+ def http_class
57+ case @method
58+ when :post then Net ::HTTP ::Post
59+ when :put then Net ::HTTP ::Put
60+ when :delete then Net ::HTTP ::Delete
61+ else
62+ Net ::HTTP ::Get
63+ end
6164 end
6265
6366 end
0 commit comments