Class: Layer::HttpClient

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

Constant Summary collapse

DEFAULT_HOST =
"https://api.layer.com"

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(app_id, api_token) ⇒ HttpClient

Returns a new instance of HttpClient.



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

def initialize(app_id, api_token)
  @app_id = app_id
  @api_token = api_token
end

Instance Attribute Details

#api_tokenObject (readonly)

Returns the value of attribute api_token.



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

def api_token
  @api_token
end

#app_idObject (readonly)

Returns the value of attribute app_id.



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

def app_id
  @app_id
end

Instance Method Details

#base_urlObject



66
67
68
# File 'lib/layer/http_client.rb', line 66

def base_url
  "#{DEFAULT_HOST}/apps/#{app_id}"
end

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



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

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

#connectionObject



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

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

#default_layer_headersObject



53
54
55
56
57
58
59
60
# File 'lib/layer/http_client.rb', line 53

def default_layer_headers
  {
    'Accept' => 'application/vnd.layer+json; version=1.0',
    'Authorization' => "Bearer #{api_token}",
    'Content-Type' => 'application/json',
    'If-None-Match' => SecureRandom.uuid
  }
end

#delete(url) ⇒ Object



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

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

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



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

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

#layer_patch_headerObject



62
63
64
# File 'lib/layer/http_client.rb', line 62

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

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



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

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

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



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

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

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



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

def run_request(method, url, options = {})
  connection.run_request(
    method,
    url,
    options[:body],
    options[:headers]
  )
end