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



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

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

#connectionObject



12
13
14
15
16
17
18
19
# 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.adapter  Faraday.default_adapter
    faraday.use Middleware::ApiErrors
  end
end

#delete(url) ⇒ Object



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

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

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



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

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

#layer_patch_headerObject



54
55
56
# File 'lib/layer/http_client.rb', line 54

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

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



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

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

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



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

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

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



42
43
44
45
46
47
48
49
50
51
52
# File 'lib/layer/http_client.rb', line 42

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

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