Class: CodeUnion::HTTPClient

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

Overview

More friendly RESTful interactions via Faraday and Addressable

Defined Under Namespace

Classes: RequestError

Instance Method Summary collapse

Constructor Details

#initialize(api_host) ⇒ HTTPClient

Returns a new instance of HTTPClient.



9
10
11
# File 'lib/codeunion/http_client.rb', line 9

def initialize(api_host)
  @api_host = api_host
end

Instance Method Details

#get(endpoint, params = {}) ⇒ Object



13
14
15
# File 'lib/codeunion/http_client.rb', line 13

def get(endpoint, params = {})
  connection.get(request_url(endpoint, params)).body
end

#post(endpoint, body = {}, params = {}) ⇒ Object



17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
# File 'lib/codeunion/http_client.rb', line 17

def post(endpoint, body = {}, params = {})
  response = connection.post do |req|
    req.url request_url(endpoint, params)
    req.headers["Content-Type"] = "application/json"
    req.body = body.to_json
  end

  unless (200..300).cover?(response.status)
    message = "POST to #{request_url(endpoint, params)} with " +
              "#{body} responded with #{response.status} and " +
              "#{response.body}"
    fail(HTTPClient::RequestError, message)
  end
  response.body
end

#request_url(endpoint, params = {}) ⇒ Object



33
34
35
# File 'lib/codeunion/http_client.rb', line 33

def request_url(endpoint, params = {})
  expand_url({ :endpoint => endpoint, :params => params })
end