Class: Ecoportal::API::Common::Client

Inherits:
Object
  • Object
show all
Defined in:
lib/ecoportal/api/common/client.rb

Instance Method Summary collapse

Constructor Details

#initialize(api_key:, version: "v1", host: "live.ecoportal.com", logger: nil) ⇒ Client

Returns a new instance of Client.



6
7
8
9
10
11
12
13
14
15
16
17
# File 'lib/ecoportal/api/common/client.rb', line 6

def initialize(api_key:, version: "v1", host: "live.ecoportal.com", logger: nil)
  @version  = version
  @api_key  = api_key
  @logger   = logger
  if host.match(/^localhost|^127\.0\.0\.1/)
    @base_uri = "http://#{host}/api/"
  else
    @base_uri = "https://#{host}/api/"
  end
  log(:info) { "#{version} client initialized pointing at #{host}" }
  log(:info) { "Api-key: #{@api_key}" }
end

Instance Method Details

#base_requestObject



63
64
65
# File 'lib/ecoportal/api/common/client.rb', line 63

def base_request
  @base_request ||= HTTP.headers("X-ApiKey" => @api_key).accept(:json)
end

#delete(path) ⇒ Object



47
48
49
50
51
52
53
# File 'lib/ecoportal/api/common/client.rb', line 47

def delete(path)
  instrument("DELETE", path) do
    request do |http|
      http.delete(url_for(path))
    end
  end
end

#get(path, params: {}) ⇒ Object



23
24
25
26
27
28
29
# File 'lib/ecoportal/api/common/client.rb', line 23

def get(path, params: {})
  instrument("GET", path, params) do
    request do |http|
      http.get(url_for(path), params: params)
    end
  end
end

#log(level, &block) ⇒ Object



19
20
21
# File 'lib/ecoportal/api/common/client.rb', line 19

def log(level, &block)
  @logger.send(level, &block) if @logger
end

#patch(path, data:) ⇒ Object



39
40
41
42
43
44
45
# File 'lib/ecoportal/api/common/client.rb', line 39

def patch(path, data:)
  instrument("PATCH", path, data) do
    request do |http|
      http.patch(url_for(path), json: data)
    end
  end
end

#post(path, data:) ⇒ Object



31
32
33
34
35
36
37
# File 'lib/ecoportal/api/common/client.rb', line 31

def post(path, data:)
  instrument("POST", path, data) do
    request do |http|
      http.post(url_for(path), json: data)
    end
  end
end

#requestObject



55
56
57
# File 'lib/ecoportal/api/common/client.rb', line 55

def request
  wrap_response yield(base_request)
end

#url_for(path) ⇒ Object



67
68
69
# File 'lib/ecoportal/api/common/client.rb', line 67

def url_for(path)
  @base_uri+@version+path
end

#wrap_response(response) ⇒ Object



59
60
61
# File 'lib/ecoportal/api/common/client.rb', line 59

def wrap_response(response)
  Ecoportal::API::Common::Response.new(response)
end