Class: Ksef::Internal::Connection

Inherits:
Object
  • Object
show all
Defined in:
lib/ksef/internal/connection.rb

Overview

Thin Faraday wrapper around the KSeF HTTP API.

All response-shape parsing and error classification lives here so the higher-level resource classes can treat the API as a typed boundary.

Constant Summary collapse

RETRY_OPTIONS =
{
  max:                 2,
  interval:            0.4,
  interval_randomness: 0.2,
  backoff_factor:      2,
  retry_statuses:      [502, 503, 504],
  methods:             %i[get head post delete put patch],
  exceptions:          [
    Errno::ETIMEDOUT,
    Faraday::TimeoutError,
    Faraday::ConnectionFailed
  ]
}.freeze
JSON_CONTENT_TYPE =
"application/json"

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(configuration) ⇒ Connection

Returns a new instance of Connection.



32
33
34
# File 'lib/ksef/internal/connection.rb', line 32

def initialize(configuration)
  @configuration = configuration
end

Instance Attribute Details

#configurationObject (readonly)

Returns the value of attribute configuration.



30
31
32
# File 'lib/ksef/internal/connection.rb', line 30

def configuration
  @configuration
end

Class Method Details

.parse_json(response) ⇒ Object

Parses a JSON response body, returning ‘{}` on empty bodies.



56
57
58
59
60
61
62
# File 'lib/ksef/internal/connection.rb', line 56

def self.parse_json(response)
  return {} if response.body.nil? || response.body.to_s.empty?

  JSON.parse(response.body)
rescue JSON::ParserError
  {}
end

Instance Method Details

#request(method, path, body: nil, headers: {}, query: {}, bearer_token: nil) ⇒ Faraday::Response

Issues an HTTP request and returns a ‘Faraday::Response`.

Parameters:

  • method (Symbol)

    :get, :post, :delete, etc.

  • path (String)

    path relative to ‘configuration.resolved_base_url`

  • body (Object, nil) (defaults to: nil)

    hash → JSON, String → raw body

  • headers (Hash) (defaults to: {})
  • query (Hash) (defaults to: {})
  • bearer_token (String, nil) (defaults to: nil)

    sent as ‘Authorization: Bearer …`

Returns:

  • (Faraday::Response)


45
46
47
48
49
50
51
52
53
# File 'lib/ksef/internal/connection.rb', line 45

def request(method, path, body: nil, headers: {}, query: {}, bearer_token: nil)
  response = http.run_request(method, expand_path(path), nil,
                              build_headers(headers, bearer_token)) do |req|
    req.params.update(query) unless query.empty?
    assign_body(req, body)
  end
  check!(response)
  response
end