Module: Brine::ClientBuilding

Included in:
Brine
Defined in:
lib/brine/client_building.rb

Overview

Allow construction of a Faraday connection with some common middleware.

Defined Under Namespace

Classes: OAuth2Params

Instance Method Summary collapse

Instance Method Details

#client_for_host(host, logging: ) ⇒ Faraday::Connection

Return a client which will send requests to ‘host`.

This will configure the client using ‘#connection_handlers`.

Parameters:

  • host (String)

    Specify the hostname to which this client will send requests.

  • logging (String) (defaults to: )

    Indicate the desired logging level for this client.

Returns:

  • (Faraday::Connection)

    Return the configured client connection.



109
110
111
112
113
114
# File 'lib/brine/client_building.rb', line 109

def client_for_host(host, logging: ENV['BRINE_LOG_HTTP'])
  @logging = logging
  Faraday.new(host) do |conn|
    connection_handlers.each{|h| h.call(conn) }
  end
end

#connection_handlersObject

Expose the handlers/middleware that will be wired while constructing a client.

This is represented as list of functions so that it can be more easily customized for unexpected use cases. It should likely be broken up a bit more sensibly and more useful insertion commands added… but it’s likely enough of a power feature and platform specific to leave pretty raw.



82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
# File 'lib/brine/client_building.rb', line 82

def connection_handlers
  @connection_handlers ||= [
    proc do |conn|
      conn.request :json
      if @oauth2
        conn.request :oauth2, @oauth2.token, :token_type => @oauth2.token_type
      end
    end,
    proc do |conn|
      if @logging
        conn.response :logger, nil, :bodies => (@logging.casecmp('DEBUG') == 0)
      end
      conn.response :json, :content_type => /\bjson$/
    end,
    proc{|conn| conn.adapter Faraday.default_adapter }
  ]
end

#use_oauth2_token(&block) ⇒ Object

Acquire an OAuth2 token with the provided configuration block.

Parameters:

  • Provide (Block)

    logic to execute with an OAuth2Params receiver; this will normally involve an OAuth2Params#fetch_from call.



69
70
71
72
# File 'lib/brine/client_building.rb', line 69

def use_oauth2_token(&block)
  @oauth2 = OAuth2Params.new
  @oauth2.instance_eval(&block)
end