Class: Layer::HttpClient

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

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(base_url, default_headers) ⇒ HttpClient

Returns a new instance of HttpClient.



7
8
9
10
# File 'lib/layer/http_client.rb', line 7

def initialize(base_url, default_headers)
  @base_url = base_url
  @default_headers = default_headers
end

Instance Attribute Details

#base_urlObject (readonly)

Returns the value of attribute base_url.



5
6
7
# File 'lib/layer/http_client.rb', line 5

def base_url
  @base_url
end

#default_headersObject (readonly)

Returns the value of attribute default_headers.



5
6
7
# File 'lib/layer/http_client.rb', line 5

def default_headers
  @default_headers
end

Instance Method Details

#call(method, url, options = {}) ⇒ Object



42
43
44
45
# File 'lib/layer/http_client.rb', line 42

def call(method, url, options = {})
  response = run_request(method, url, options)
  response.body.empty? ? true : JSON.parse(response.body)
end

#connectionObject



12
13
14
15
16
17
18
19
20
# File 'lib/layer/http_client.rb', line 12

def connection
  @connection ||= Faraday.new(url: base_url) do |faraday|
    faraday.headers = default_headers
    faraday.request  :url_encoded
    faraday.request  :multipart
    faraday.adapter  Faraday.default_adapter
    faraday.use Middleware::ApiErrors
  end
end

#delete(url) ⇒ Object



38
39
40
# File 'lib/layer/http_client.rb', line 38

def delete(url)
  call(:delete, url)
end

#get(url, options = {}) ⇒ Object



22
23
24
# File 'lib/layer/http_client.rb', line 22

def get(url, options = {})
  call(:get, url, options)
end

#layer_patch_headerObject



59
60
61
# File 'lib/layer/http_client.rb', line 59

def layer_patch_header
  { 'Content-Type' => 'application/vnd.layer-patch+json' }
end

#patch(url, options = {}) ⇒ Object



34
35
36
# File 'lib/layer/http_client.rb', line 34

def patch(url, options = {})
  call(:patch, url, options)
end

#post(url, options = {}) ⇒ Object



30
31
32
# File 'lib/layer/http_client.rb', line 30

def post(url, options = {})
  call(:post, url, options)
end

#put(url, options = {}) ⇒ Object



26
27
28
# File 'lib/layer/http_client.rb', line 26

def put(url, options = {})
  call(:put, url, options)
end

#run_request(method, url, options = {}) ⇒ Object



47
48
49
50
51
52
53
54
55
56
57
# File 'lib/layer/http_client.rb', line 47

def run_request(method, url, options = {})
  headers = options[:headers] || {}
  headers["If-None-Match"] = SecureRandom.uuid

  connection.run_request(
    method,
    url,
    options[:body],
    headers
  )
end