Class: ExoBasic::JsonHttpClient

Inherits:
Object
  • Object
show all
Defined in:
lib/exobasic/http/json_http_client.rb

Class Method Summary collapse

Class Method Details

.do_delete_request(url, headers = {}) ⇒ Object



53
54
55
56
57
58
59
60
61
# File 'lib/exobasic/http/json_http_client.rb', line 53

def self.do_delete_request(url, headers={})
  uri, http = JsonHttpClient.prepare_http(url)
  req       = Net::HTTP::Delete.new(uri.request_uri)
  headers.each { |k, v| req[k] = v }

  resp = http.request(req)

  [resp.code, resp.message]
end

.do_get_request(url, headers = {}) ⇒ Object



29
30
31
32
33
34
35
36
37
# File 'lib/exobasic/http/json_http_client.rb', line 29

def self.do_get_request(url, headers={})
  uri, http = JsonHttpClient.prepare_http(url)
  req       = Net::HTTP::Get.new(uri.request_uri)
  headers.each { |k, v| req[k] = v }

  resp = http.request(req)

  [resp.code, JSON.load(resp.body)]
end

.do_post_request(url, headers = {}, payload) ⇒ Object



39
40
41
42
43
44
45
46
47
48
49
50
51
# File 'lib/exobasic/http/json_http_client.rb', line 39

def self.do_post_request(url, headers={}, payload)
  uri, http = JsonHttpClient.prepare_http(url)
  req       = Net::HTTP::Post.new(uri.request_uri)
  headers.each { |k, v| req[k] = v }
  req['Content-Type'] = 'application/json'
  if !payload.nil?
    req.body = payload.to_json
  end

  resp = http.request(req)

  [resp.code, JSON.load(resp.body)]
end

.get_response_errors(response) ⇒ Object



63
64
65
66
67
68
69
70
71
72
73
74
75
76
# File 'lib/exobasic/http/json_http_client.rb', line 63

def self.get_response_errors(response)
  if response[1].is_a?(Hash) && response[1].key?('errors')
    errs = response[1]['errors']
    if response[1]['errors'].is_a?(Array)
      errs
    elsif response[1]['errors'].is_a?(String)
      [errs]
    else
      [errs.to_s]
    end
  else
    []
  end
end

.prepare_http(url) ⇒ Object



7
8
9
10
11
12
13
14
15
16
17
18
# File 'lib/exobasic/http/json_http_client.rb', line 7

def self.prepare_http(url)
  if !url.start_with?('http') && !url.start_with?('https')
    url = "https://#{url}"
  end
  uri  = URI.parse(url)
  http = Net::HTTP.new(uri.host, uri.port)
  if url.start_with?('https')
    http.use_ssl = true
  end

  [uri, http]
end

.url_with_parameters(url, parameters) ⇒ Object



20
21
22
23
24
25
26
27
# File 'lib/exobasic/http/json_http_client.rb', line 20

def self.url_with_parameters(url, parameters)
  parameters_prime = parameters.map { |k, v| "#{k}=#{v}" }.join('&')
  if !parameters_prime.empty?
    "#{url}?#{parameters_prime}"
  else
    url
  end
end