Class: Lutaml::Hal::Client

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

Overview

HAL Client for making HTTP requests to HAL APIs

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(options = {}) ⇒ Client

Returns a new instance of Client.



15
16
17
18
19
20
21
22
23
24
# File 'lib/lutaml/hal/client.rb', line 15

def initialize(options = {})
  @api_url = options[:api_url] || raise(ArgumentError, 'api_url is required')
  @connection = options[:connection] || create_connection
  @params_default = options[:params_default] || {}
  @debug = options[:debug] || !ENV['DEBUG_API'].nil?
  @cache = options[:cache] || {}
  @cache_enabled = options[:cache_enabled] || false

  @api_url = strip_api_url(@api_url)
end

Instance Attribute Details

#api_urlObject (readonly)

Returns the value of attribute api_url.



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

def api_url
  @api_url
end

#connectionObject (readonly)

Returns the value of attribute connection.



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

def connection
  @connection
end

#last_responseObject (readonly)

Returns the value of attribute last_response.



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

def last_response
  @last_response
end

Instance Method Details

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

Make a GET request to the API



39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
# File 'lib/lutaml/hal/client.rb', line 39

def get(url, params = {})
  cache_key = "#{url}:#{params.to_json}"

  return @cache[cache_key] if @cache_enabled && @cache.key?(cache_key)

  @last_response = @connection.get(url, params)

  response = handle_response(@last_response, url)

  @cache[cache_key] = response if @cache_enabled
  response
rescue Faraday::ConnectionFailed => e
  raise ConnectionError, "Connection failed: #{e.message}"
rescue Faraday::TimeoutError => e
  raise TimeoutError, "Request timed out: #{e.message}"
rescue Faraday::ParsingError => e
  raise ParsingError, "Response parsing error: #{e.message}"
rescue Faraday::Adapter::Test::Stubs::NotFound => e
  raise LinkResolutionError, "Resource not found: #{e.message}"
end

#get_by_url(url, params = {}) ⇒ Object

Get a resource by its full URL



32
33
34
35
36
# File 'lib/lutaml/hal/client.rb', line 32

def get_by_url(url, params = {})
  # Strip API endpoint if it's included
  path = strip_api_url(url)
  get(path, params)
end

#strip_api_url(url) ⇒ Object

Strip any trailing slash from the API URL



27
28
29
# File 'lib/lutaml/hal/client.rb', line 27

def strip_api_url(url)
  url.sub(%r{/\Z}, '')
end