Class: DIT3::Api::Client

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

Instance Method Summary collapse

Constructor Details

#initialize(host, client_id, client_secret) ⇒ Client

Returns a new instance of Client.



11
12
13
14
15
16
17
18
19
20
# File 'lib/dit3/api/client.rb', line 11

def initialize(host, client_id, client_secret)
    @api = host + "/api"
    @oauth_client = OAuthClient.new(host, client_id, client_secret)
    @token = get_token @oauth_client
    @request_factory = {
        "GET" => method(:get_request),
        "POST" => method(:post_request),
        "DELETE" => method(:delete_request)
    }
end

Instance Method Details

#delete(endpoint) ⇒ Object



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

def delete endpoint
    exec_request("DELETE", endpoint)
end

#exec_request(method, endpoint) {|request| ... } ⇒ Object

Yields:

  • (request)


26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
# File 'lib/dit3/api/client.rb', line 26

def exec_request method, endpoint
    uri = URI(@api + endpoint)
    request = @request_factory[method].call(uri)
    http = get_http uri

    yield(request) if block_given?

    response = http.request request
    if (!response.kind_of? Net::HTTPSuccess)
        raise ApiError.new(response), "Failed to execute #{method} #{endpoint} request - #{response.code}"
    end
    if !response.body.nil?
        JSON.parse response.body
    else
        nil
    end
end

#get(endpoint) ⇒ Object



44
45
46
# File 'lib/dit3/api/client.rb', line 44

def get endpoint
    exec_request("GET", endpoint)
end

#post(endpoint, data) ⇒ Object



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

def post endpoint, data
    exec_request("POST", endpoint) do |request|
        request['Content-Type'] = 'application/json'
        request.body = data.to_json
    end
end

#tenantsObject



22
23
24
# File 'lib/dit3/api/client.rb', line 22

def tenants
    Wrappers::Tenants.new(self)
end