Class: RailsCosmos::Http::Client

Inherits:
Object
  • Object
show all
Defined in:
lib/rails_cosmos/http/client.rb

Overview

RailsCosmos::Http::Client

A wrapper around Faraday for making HTTP requests with enhanced logging and error handling. This class provides a simple interface for sending requests to external APIs and logging request/response details for observability.

Examples:

Creating a client instance

client = RailsCosmos::Http::Client.new(
  url: "https://api.example.com",
  service: "ExampleService",
  adapter: :typhoeus
)

Making a GET request

response = client.get("/endpoint", headers: { "Authorization" => "Bearer token" })

Making a POST request with a payload

response = client.post(
  "/endpoint",
  payload: { key: "value" },
  headers: { "Content-Type" => "application/json" }
)

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(url:, service:, adapter: :typhoeus) ⇒ Client

Returns a new instance of Client.



36
37
38
39
40
41
# File 'lib/rails_cosmos/http/client.rb', line 36

def initialize(url:, service:, adapter: :typhoeus)
  @url = url
  @service = service
  @adapter = adapter
  @conn = build_connection
end

Instance Attribute Details

#adapterSymbol (readonly)

The Faraday adapter to use for making requests.

Returns:

  • (Symbol)

    the current value of adapter



35
36
37
# File 'lib/rails_cosmos/http/client.rb', line 35

def adapter
  @adapter
end

#serviceString (readonly)

The name of the service for logging purposes.

Returns:

  • (String)

    the current value of service



35
36
37
# File 'lib/rails_cosmos/http/client.rb', line 35

def service
  @service
end

#urlString (readonly)

The base URL for the HTTP client.

Returns:

  • (String)

    the current value of url



35
36
37
# File 'lib/rails_cosmos/http/client.rb', line 35

def url
  @url
end

Instance Method Details

#request(method, endpoint, payload: {}, headers: {}) ⇒ Object



43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
# File 'lib/rails_cosmos/http/client.rb', line 43

def request(method, endpoint, payload: {}, headers: {})
  start_at = Time.zone.now
  response = @conn.send(method, endpoint) do |req|
    req.headers = headers
    req.body = payload.to_json if %i[post put patch delete].include?(method)
    log_request(method: method, url: req.path, headers: headers, payload: payload)
  end

  response_time = Time.zone.now - start_at

  log_response(
    method: method, success: response.success?,
    time: response_time, status: response.status, url: endpoint,
    headers: response.headers, body: response.body
  )

  Response.new(response)
end