Module: Convoy::ApiOperations::Request

Included in:
Convoy::ApiResource
Defined in:
lib/convoy/api_operations/request.rb

Instance Method Summary collapse

Instance Method Details

#send_request(uri, method, config = Convoy.config, **kwargs) ⇒ Object



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
52
53
54
55
# File 'lib/convoy/api_operations/request.rb', line 7

def send_request(uri, method, config = Convoy.config, **kwargs)
  # Determine URL.
  uri = URI(uri)
  params = kwargs[:params].nil? ? {} : kwargs[:params]
  uri.query = URI.encode_www_form(params) unless params.empty?

  # Build Request.
  request = case method.downcase.to_sym
            when :post
              req = Net::HTTP::Post.new(uri.request_uri)
              data = kwargs[:data].nil? ? {} : kwargs[:data]
              req['Content-Type'] = 'application/json'
              req.body = JSON.dump(data)
              
              req
            when :get
              Net::HTTP::Get.new(uri.request_uri)
            when :delete
              Net::HTTP::Delete.new(uri.request_uri)
            when :put
              req = Net::HTTP::Put.new(uri.request_uri)
              data = kwargs[:data].nil? ? {} : kwargs[:data]
              req['Content-Type'] = 'application/json'
              req.body = JSON.dump(data)

              req
            end

  if !config.api_key.nil?
    request['Authorization'] = "Bearer #{config.api_key}"
  end

  # Build HTTP Client.
  client = Net::HTTP.new(uri.host, uri.port)
  client.use_ssl = config.ssl
  client.open_timeout = 10
  client.read_timeout = 10
  client.continue_timeout = 10
  client.ssl_timeout = 10

  client.set_debug_output $stderr if config.debug

  # Make request.
  http_response = client.request(request)
  @response = JSON.parse(http_response.body)

  self
  # TODO: Perform err checks.
end