Class: Moyasar::HTTPClient

Inherits:
Object
  • Object
show all
Defined in:
lib/moyasar/http_client.rb

Constant Summary collapse

METHOD_CLASS =
{
  head:   Net::HTTP::Head,
  get:    Net::HTTP::Get,
  post:   Net::HTTP::Post,
  put:    Net::HTTP::Put,
  delete: Net::HTTP::Delete
}.freeze
DEFAULT_HEADERS =
{
  'Content-Type' => 'application/json'
}.freeze

Instance Method Summary collapse

Constructor Details

#initialize(endpoint) ⇒ HTTPClient

Returns a new instance of HTTPClient.



15
16
17
18
19
# File 'lib/moyasar/http_client.rb', line 15

def initialize(endpoint)
  uri = URI.parse(endpoint)
  @http = Net::HTTP.new(uri.host, uri.port)
  @http.use_ssl = true
end

Instance Method Details

#request(method, path, key = nil, params = {}, headers = {}) ⇒ Object



21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
# File 'lib/moyasar/http_client.rb', line 21

def request(method, path, key = nil, params = {}, headers = {})
  case method
  when :get
    full_path = encode_path_params(path, params)
    request = METHOD_CLASS[method.to_sym].new(full_path, DEFAULT_HEADERS)
  else
    request = METHOD_CLASS[method.to_sym].new(path, DEFAULT_HEADERS)
    # post_data = URI.encode_www_form(params)
    request.body = params.to_json
  end

  request.basic_auth(key, '') unless key.nil?

  @http.request(request)
end

#request_json(method, path, key = nil, params = {}, headers = {}) ⇒ Object



37
38
39
40
41
42
43
44
# File 'lib/moyasar/http_client.rb', line 37

def request_json(method, path, key = nil, params = {}, headers = {})
  response = request(method, path, key, params, headers)
  body = JSON.parse(response.body)

  OpenStruct.new(code: response.code.to_i, body: body)
rescue JSON::ParserError
  response
end