class ApiStruct::Client

Constants

DEFAULT_HEADERS
HTTP_METHODS
URL_OPTION_REGEXP

Attributes

client[R]

Public Class Methods

method_missing(method_name, *args, &block) click to toggle source
Calls superclass method
# File lib/api_struct/client.rb, line 11
def self.method_missing(method_name, *args, &block)
  endpoints = Settings.config.endpoints
  return super unless endpoints.keys.include?(method_name)

  define_method(:api_root) { endpoints[method_name][:root] }
  define_method(:default_params) { endpoints[method_name][:params] || {} }
  define_method(:default_path) { first_arg(args) }

  define_method(:headers) do
    endpoints[method_name][:headers]
  end
end
new() click to toggle source
# File lib/api_struct/client.rb, line 37
def initialize
  api_settings_exist
  client_headers = headers || DEFAULT_HEADERS
  @client = HTTP::Client.new(headers: client_headers)
end

Private Instance Methods

api_settings_exist() click to toggle source
# File lib/api_struct/client.rb, line 83
def api_settings_exist
  return if respond_to?(:api_root)
  raise RuntimeError, "\nSet api configuration for #{self.class}."
end
build_url(args, options) click to toggle source
# File lib/api_struct/client.rb, line 64
def build_url(args, options)
  suffix = to_path(args)
  prefix = to_path(options.delete(:prefix))
  path = to_path(options.delete(:path) || default_path)

  replace_optional_params(to_path(api_root, prefix, path, suffix), options)
end
failure(response) click to toggle source
# File lib/api_struct/client.rb, line 55
def failure(response)
  result = ApiStruct::Errors::Client.new(response)
  Dry::Monads::Failure(result)
end
first_arg(args) click to toggle source
# File lib/api_struct/client.rb, line 60
def first_arg(args)
  args.first.to_s
end
replace_optional_params(url, options) click to toggle source
# File lib/api_struct/client.rb, line 76
def replace_optional_params(url, options)
  url.gsub(URL_OPTION_REGEXP) do
    value = options.delete($1.to_sym)
    value ? "/#{value}" : ''
  end
end
success(response) click to toggle source
# File lib/api_struct/client.rb, line 49
def success(response)
  body = response.body.to_s
  result = !body.empty? ? JSON.parse(body, symbolize_names: true) : nil
  Dry::Monads::Success(result)
end
to_path(*args) click to toggle source
# File lib/api_struct/client.rb, line 72
def to_path(*args)
  Array(args).reject { |o| o.respond_to?(:empty?) ? o.empty? : !o }.join('/')
end
wrap(response) click to toggle source
# File lib/api_struct/client.rb, line 45
def wrap(response)
  response.status < 300 ? success(response) : failure(response)
end