Class: ProviderKit::JsonClient

Inherits:
Object
  • Object
show all
Defined in:
lib/provider_kit/json_client.rb

Overview

Generic interface for working with JSON-based APIs.

This class is just a simple wrapper around net/http so we don't need to use a third-party networking library for basic stuff.

Defined Under Namespace

Classes: LogSubscriber

Constant Summary collapse

DEFAULT_HEADERS =
{
  "Accept" => "application/json",
  "User-Agent" => "ProviderKitBot/1.0 (+https://example.com)"
}

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(base_url, **options) ⇒ JsonClient

Returns a new instance of JsonClient.



20
21
22
23
24
25
# File 'lib/provider_kit/json_client.rb', line 20

def initialize(base_url, **options)
  @base_url         = base_url
  @default_headers  = options[:headers].presence || DEFAULT_HEADERS
  @default_params   = options[:params].presence || {}
  @default_mode     = options[:mode].presence || :json
end

Instance Attribute Details

#base_urlObject (readonly)

Returns the value of attribute base_url.



15
16
17
# File 'lib/provider_kit/json_client.rb', line 15

def base_url
  @base_url
end

#default_headersObject (readonly)

Returns the value of attribute default_headers.



16
17
18
# File 'lib/provider_kit/json_client.rb', line 16

def default_headers
  @default_headers
end

#default_modeObject (readonly)

Returns the value of attribute default_mode.



18
19
20
# File 'lib/provider_kit/json_client.rb', line 18

def default_mode
  @default_mode
end

#default_paramsObject (readonly)

Returns the value of attribute default_params.



17
18
19
# File 'lib/provider_kit/json_client.rb', line 17

def default_params
  @default_params
end

Instance Method Details

#request(path, method: :get, params: {}, headers: {}, mode: nil) ⇒ Object



36
37
38
39
40
41
42
43
44
# File 'lib/provider_kit/json_client.rb', line 36

def request(path, method: :get, params: {}, headers: {}, mode: nil)
  path      = "/#{ path }".gsub(%r{//}, "/")
  url       = "#{ base_url }#{ path }"
  headers   = default_headers.merge(headers)
  params    = default_params.merge(params)
  mode      = mode.presence || default_mode

  JsonRequest.new(url, method:, params:, headers:, mode:)
end