Class: Fbe::Middleware::Trace

Inherits:
Faraday::Middleware
  • Object
show all
Defined in:
lib/fbe/middleware/trace.rb

Overview

Faraday middleware that traces all API calls.

This middleware records all HTTP requests and responses in a trace array, capturing method, URL, status, and timing information for debugging and monitoring purposes.

Author

Yegor Bugayenko ([email protected])

Copyright

Copyright © 2024-2025 Zerocracy

License

MIT

Examples:

Usage in Faraday middleware stack

trace = []
connection = Faraday.new do |f|
  f.use Fbe::Middleware::Trace, trace
end
connection.get('/api/endpoint')
trace.first[:method] #=> :get
trace.first[:url] #=> 'https://example.com/api/endpoint'
trace.first[:status] #=> 200

Instance Method Summary collapse

Constructor Details

#initialize(app, trace, ignores: []) ⇒ Trace

Initializes the trace middleware.

which will be ignored

Parameters:

  • app (Object)

    The next middleware in the stack

  • trace (Array)

    The array to store trace entries

  • ignores (Array<Symbol>) (defaults to: [])

    The array of symbols (see Faraday::HttpCache::CACHE_STATUSES),



36
37
38
39
40
# File 'lib/fbe/middleware/trace.rb', line 36

def initialize(app, trace, ignores: [])
  super(app)
  @trace = trace
  @ignores = ignores
end

Instance Method Details

#call(env) ⇒ Faraday::Response

Processes the HTTP request and records trace information.

Parameters:

  • env (Faraday::Env)

    The request environment

Returns:

  • (Faraday::Response)

    The response from the next middleware



46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
# File 'lib/fbe/middleware/trace.rb', line 46

def call(env)
  entry = {
    method: env.method,
    url: env.url.to_s,
    started_at: Time.now
  }
  @app.call(env).on_complete do |response_env|
    next if !@ignores.empty? &&
            response_env[:http_cache_trace] &&
            (response_env[:http_cache_trace] & @ignores).size.positive?
    finished = Time.now
    duration = finished - entry[:started_at]
    entry[:status] = response_env.status
    entry[:finished_at] = finished
    entry[:duration] = duration
    @trace << entry
  end
end