class MetalArchives::HTTPClient

Generic HTTP client

Attributes

endpoint[R]
metrics[R]

Public Class Methods

new(endpoint = MetalArchives.config.endpoint) click to toggle source
# File lib/metal_archives/http_client.rb, line 12
def initialize(endpoint = MetalArchives.config.endpoint)
  @endpoint = endpoint
  @metrics = { hit: 0, miss: 0 }
end

Public Instance Methods

get(path, params = {}) click to toggle source
# File lib/metal_archives/http_client.rb, line 17
def get(path, params = {})
  response = http
    .get(url_for(path), params: params)

  # Log cache status
  status = response.headers["x-cache-status"]&.downcase&.to_sym
  MetalArchives.config.logger.info "Cache #{status} for #{path}" if status

  case status
  when :hit
    metrics[:hit] += 1
  when :miss, :bypass, :expired, :stale, :updating, :revalidated
    metrics[:miss] += 1
  end
  raise Errors::InvalidIDError, response if response.code == 404
  raise Errors::APIError, response unless response.status.success?

  response
end

Private Instance Methods

headers() click to toggle source
# File lib/metal_archives/http_client.rb, line 51
def headers
  {
    user_agent: "#{MetalArchives.config.app_name}/#{MetalArchives.config.app_version} (#{MetalArchives.config.app_contact})",
    accept: "application/json",
  }
end
http() click to toggle source
# File lib/metal_archives/http_client.rb, line 39
def http
  @http ||= HTTP
    .headers(headers)
    .use(logging: { logger: MetalArchives.config.logger })
    .encoding("utf-8")

  return @http unless MetalArchives.config.endpoint_user && MetalArchives.config.endpoint_password

  @http
    .basic_auth(user: MetalArchives.config.endpoint_user, pass: MetalArchives.config.endpoint_password)
end
url_for(path) click to toggle source
# File lib/metal_archives/http_client.rb, line 58
def url_for(path)
  "#{endpoint}#{path}"
end