Class: RailsCosmos::Http::Client
- Inherits:
-
Object
- Object
- RailsCosmos::Http::Client
- 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.
Instance Attribute Summary collapse
-
#adapter ⇒ Symbol
readonly
The Faraday adapter to use for making requests.
-
#service ⇒ String
readonly
The name of the service for logging purposes.
-
#url ⇒ String
readonly
The base URL for the HTTP client.
Instance Method Summary collapse
-
#initialize(url:, service:, adapter: :typhoeus) ⇒ Client
constructor
A new instance of Client.
- #request(method, endpoint, payload: {}, headers: {}) ⇒ Object
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
#adapter ⇒ Symbol (readonly)
The Faraday adapter to use for making requests.
35 36 37 |
# File 'lib/rails_cosmos/http/client.rb', line 35 def adapter @adapter end |
#service ⇒ String (readonly)
The name of the service for logging purposes.
35 36 37 |
# File 'lib/rails_cosmos/http/client.rb', line 35 def service @service end |
#url ⇒ String (readonly)
The base URL for the HTTP client.
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 |