Class: Oyi::Client

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

Overview

The REST client that talks to OY API

Class Method Summary collapse

Class Method Details

.configure(api_url:, api_username:, api_key:) ⇒ Object



7
8
9
10
11
# File 'lib/oyi/client.rb', line 7

def configure(api_url:, api_username:, api_key:)
  @api_url = api_url
  @api_username = api_username
  @api_key = api_key
end

.configured?Boolean

Returns:

  • (Boolean)


13
14
15
# File 'lib/oyi/client.rb', line 13

def configured?
  @api_url && @api_username && @api_key
end

.error_class(status) ⇒ Object



53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
# File 'lib/oyi/client.rb', line 53

def error_class(status)
  case status
  when HTTP_BAD_REQUEST_CODE
    BadRequestError
  when HTTP_UNAUTHORIZED_CODE
    UnauthorizedError
  when HTTP_FORBIDDEN_CODE
    ForbiddenError
  when HTTP_NOT_FOUND_CODE
    NotFoundError
  when HTTP_UNPROCESSABLE_ENTITY_CODE
    UnprocessableEntityError
  else
    ApiError
  end
end

.request(http_method:, endpoint:, params: nil) ⇒ Object

Raises:



17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
# File 'lib/oyi/client.rb', line 17

def request(http_method:, endpoint:, params: nil)
  raise Error.new(message: 'Oyi client not configured') unless configured?

  begin
    response = RestClient::Request.execute method: http_method, url: "#{@api_url}#{endpoint}",
                                           payload: params&.to_json, headers: {
                                             'Content-Type': 'application/json',
                                             'Accept': 'application/json',
                                             'X-OY-Username': @api_username,
                                             'X-Api-Key': @api_key
                                           }
    @status = response.code
    @message = begin
              JSON.parse(response.body)
               rescue JSON::ParserError
                 response.body
            end
  rescue RestClient::RequestFailed => e
    @status = e.http_code
    @message = e.message
  end
  custom_status = @message['status']
  if @status == HTTP_OK_CODE
    raise ApiError.new(message: @message['message']) if custom_status == false

    custom_error_code = custom_status.is_a?(Hash) && custom_status['code']
    if custom_error_code && !VALID_CODES.include?(custom_error_code)
      raise ApiError.new(message: @message['status']&.[]('message'))
    end

    return @message
  end

  raise error_class(@status).new(status: @status, message: @message)
end