Module: Schwab::Connection

Defined in:
lib/schwab/connection.rb

Overview

HTTP connection builder for Schwab API

Class Method Summary collapse

Class Method Details

.build(access_token: nil, config: nil) ⇒ Faraday::Connection

Build a Faraday connection with the configured middleware stack



16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
# File 'lib/schwab/connection.rb', line 16

def build(access_token: nil, config: nil)
  config ||= Schwab.configuration || Configuration.new

  Faraday.new(url: config.api_base_url) do |conn|
    # Request middleware (executed in order)
    conn.request(:json) # Encode request bodies as JSON
    conn.request(:authorization, "Bearer", access_token) if access_token

    # Response middleware (executed in reverse order)
    conn.response(:json, content_type: /\bjson$/) # Parse JSON responses
    conn.response(:raise_error) # Raise exceptions for 4xx/5xx responses
    conn.response(:logger, config.logger, { headers: false, bodies: false }) if config.logger

    # Adapter (must be last)
    conn.adapter(config.faraday_adapter)

    # Connection options
    conn.options.timeout = config.timeout
    conn.options.open_timeout = config.open_timeout
  end
end

.build_with_refresh(access_token:, refresh_token: nil, on_token_refresh: nil, config: nil) ⇒ Faraday::Connection

Build a connection with automatic token refresh capability



45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
# File 'lib/schwab/connection.rb', line 45

def build_with_refresh(access_token:, refresh_token: nil, on_token_refresh: nil, config: nil)
  config ||= Schwab.configuration || Configuration.new

  Faraday.new(url: config.api_base_url) do |conn|
    # Request middleware
    conn.request(:json)

    # Custom middleware for token refresh will be added here
    if refresh_token
      conn.use(
        Middleware::TokenRefresh,
        access_token: access_token,
        refresh_token: refresh_token,
        client_id: config.client_id,
        client_secret: config.client_secret,
        on_token_refresh: on_token_refresh,
      )
    else
      conn.request(:authorization, "Bearer", access_token)
    end

    # Response middleware
    conn.response(:json, content_type: /\bjson$/)
    conn.response(:raise_error)
    conn.response(:logger, config.logger, { headers: false, bodies: false }) if config.logger

    # Adapter
    conn.adapter(config.faraday_adapter)

    # Connection options
    conn.options.timeout = config.timeout
    conn.options.open_timeout = config.open_timeout
  end
end