Class: PatientHttp::RequestPreparer

Inherits:
Object
  • Object
show all
Defined in:
lib/patient_http/request_preparer.rb

Overview

Prepares a Request to be sent: resolves any secret references, sets the send-time headers (x-request-id and the default user-agent), and invokes any preprocessors attached to the request.

Defined Under Namespace

Classes: PreprocessorNotFoundError

Instance Method Summary collapse

Constructor Details

#initialize(config) ⇒ RequestPreparer

Returns a new instance of RequestPreparer.

Parameters:

  • config (Configuration)

    the configuration holding secrets and preprocessors



12
13
14
# File 'lib/patient_http/request_preparer.rb', line 12

def initialize(config)
  @config = config
end

Instance Method Details

#prepare(request, request_id) ⇒ OutgoingRequest

Prepare a request for sending.

Secret references in the headers and query params are resolved first, then the x-request-id and default user-agent headers are set, and finally each preprocessor attached to the request is invoked in order with the outgoing request. Each preprocessor sees any changes made by the ones before it.

Parameters:

  • request (Request)

    the request to prepare

  • request_id (String)

    unique request identifier set as the x-request-id header

Returns:

  • (OutgoingRequest)

    the outgoing request with the final URL and headers

Raises:



27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
# File 'lib/patient_http/request_preparer.rb', line 27

def prepare(request, request_id)
  headers = @config.secret_manager.resolve_headers(request.headers.to_h)
  headers["x-request-id"] = request_id
  headers["user-agent"] ||= @config.user_agent if @config.user_agent
  url = @config.secret_manager.resolve_url(request.url, request.secret_params)

  outgoing = OutgoingRequest.new(
    http_method: request.http_method,
    url: url,
    headers: HttpHeaders.new(headers),
    body: request.body
  )

  request.preprocessors.each do |name|
    preprocessor = @config.preprocessor(name)
    unless preprocessor
      raise PreprocessorNotFoundError.new("No preprocessor registered for #{name.inspect}")
    end

    preprocessor.call(outgoing)
  end

  outgoing
end