Class: Ja::API

Inherits:
Object
  • Object
show all
Includes:
Methods
Defined in:
lib/ja/api.rb

Constant Summary collapse

LOG_LINE =
"%{verb} %{url} responded with %{status} %{reason}"

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(client: HTTP, url: nil, logger: Ja.logger, log_line: LOG_LINE) ⇒ API

Returns a new instance of API.



10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
# File 'lib/ja/api.rb', line 10

def initialize(client:   HTTP,
               url:      nil,
               logger:   Ja.logger,
               log_line: LOG_LINE)

  @client = client
  @logger = logger
  @log_line = log_line
  @url = url
  if url
    uri = URI.parse(url)
    if uri.user || uri.password
      @client = @client.basic_auth(user: uri.user, pass: uri.password)
      uri.user = nil
      uri.password = nil
      @url = uri.to_s
    end
  end
  @semantic_logging = Ja.enable_semantic_logging? || (defined?(SemanticLogger) && logger.is_a?(SemanticLogger::Logger))
end

Instance Attribute Details

#clientObject (readonly)

Returns the value of attribute client.



31
32
33
# File 'lib/ja/api.rb', line 31

def client
  @client
end

#log_lineObject (readonly)

Returns the value of attribute log_line.



31
32
33
# File 'lib/ja/api.rb', line 31

def log_line
  @log_line
end

#loggerObject (readonly)

Returns the value of attribute logger.



31
32
33
# File 'lib/ja/api.rb', line 31

def logger
  @logger
end

#urlObject (readonly)

Returns the value of attribute url.



31
32
33
# File 'lib/ja/api.rb', line 31

def url
  @url
end

Instance Method Details

#full_url(path) ⇒ Object



51
52
53
54
55
56
57
# File 'lib/ja/api.rb', line 51

def full_url(path)
  if url
    File.join(url, path)
  else
    path
  end
end

#request(verb, uri, options = {}) ⇒ Object



33
34
35
36
37
38
39
40
# File 'lib/ja/api.rb', line 33

def request(verb, uri, options = {})
  full_uri = full_url(uri)
  start_time = now
  client_with_request_id = client.headers("X-Request-Id" => Thread.current[:request_id])
  response = client_with_request_id.request(verb, full_uri, options)
  log_response(response, start_time, verb, full_uri, options)
  response
end

#request!(verb, uri, options = {}) ⇒ Object



42
43
44
45
46
47
48
49
# File 'lib/ja/api.rb', line 42

def request!(verb, uri, options = {})
  response = request(verb, uri, options)
  if (100..399).cover?(response.status)
    response
  else
    fail Error.to_exception(verb, full_url(uri), response)
  end
end