Skip to content

Interceptors

Matt Muller edited this page Apr 12, 2024 · 5 revisions

Interceptors provide lifecycle hooks into the SDK. Interceptors have the ability to read or modify the input, output, request, or response objects during operation execution.

Usage

Interceptors are any class that responds to one or more lifecycle hook methods. These hook methods take a single context argument which is an InterceptorContext object. Depending on the hook's location within the request, the context will have the input Type, Hearth::Request, Hearth::Response, Hearth::Output and Logger objects.

class NetworkInterceptor
  def read_before_transmit(context)
    context.logger.info("request headers: #{context.request.headers.to_h}")
    @time = Time.now
  end

  def read_after_transmit(context)
    context.logger.info("request headers: #{context.request.headers.to_h}")
    context.logger.info("request time is: #{Time.now - @time}")
  end
end
# => :read_after_transmit

interceptors = Hearth::InterceptorList.new([NetworkInterceptor.new])
# => #<Hearth::InterceptorList ... >

# Configure interceptor onto the Client
client = HighScoreService::Client.new(
  endpoint: 'http://127.0.0.1:3000',
  interceptors: interceptors
)
# => #<HighScoreService::Client ... >

client.list_high_scores
# log request headers: { ... }
# log response headers: { ... }
# log request time is: ...
# => #<Hearth::Output @data=... >

Interceptor Ordering

The interceptor ordering is as follows:

  1. Interceptors registered to the instance of that Client.
  2. Interceptors passed as options to operation calls.

Note: Unlike other configuration, Interceptors passed as options to operation calls are additive and do not override other interceptors configured on the Client.

# These are invoked first, if any.
client.config.interceptors
# => #<Hearth::InterceptorList ... >

# Then, these are invoked, if any
more_interceptors = Hearth::InterceptorList.new([YetAnotherInterceptor.new])
# => #<Hearth::InterceptorList ... >
client.list_high_scores({}, interceptors: more_interceptors)

Available hooks

All hooks and hook documentation is defined in hearth/interceptor.rb.