Module: TocDoc::Connection

Included in:
Client
Defined in:
lib/toc_doc/core/connection.rb

Overview

Faraday-based HTTP connection and request helpers.

Included into Client to provide low-level HTTP verbs (get, post, put, patch, delete, head), a memoised Faraday connection, pagination support, and response tracking.

#get and #paginate are public so that model classes (e.g. Availability) can call them via TocDoc.client; all other HTTP verb methods remain private.

See Also:

Instance Attribute Summary collapse

Instance Method Summary collapse

Instance Attribute Details

#last_responseFaraday::Response?

The most-recent raw Faraday response, set after every request.

Returns:

  • (Faraday::Response, nil)


21
22
23
# File 'lib/toc_doc/core/connection.rb', line 21

def last_response
  @last_response
end

Instance Method Details

#get(path, options = {}) ⇒ Object

Perform a GET request.

Parameters:

  • path (String)

    API path (relative to TocDoc::Configurable#api_endpoint)

  • options (Hash) (defaults to: {})

    query / header options forwarded to #request

Returns:

  • (Object)

    parsed response body



30
31
32
# File 'lib/toc_doc/core/connection.rb', line 30

def get(path, options = {})
  request(:get, path, nil, options)
end

#paginate(path, options = {}) {|acc, last_response| ... } ⇒ Object

Performs a paginated GET, accumulating results across pages.

Behaves exactly like #get when no block is given.

When a block is provided, it is yielded after every page fetch — including the first — with +(accumulator, last_response)+. The block must:

  1. Detect whether it is a continuation call by comparing object identity: acc.equal?(last_response.body) is true only on the first yield, when the accumulator is the first-page body. On subsequent yields the block should merge last_response.body into acc.
  2. Return a Hash of options to pass to the next #get call (pagination continues), or nil / false to halt.

Parameters:

  • path (String)

    the API path

  • options (Hash) (defaults to: {})

    query / header options forwarded to every request

Yield Parameters:

  • acc (Object)

    the growing accumulator (first-page body initially)

  • last_response (Faraday::Response)

    the most-recent raw response

Yield Returns:

  • (Hash, nil)

    next-page options, or +nil+/+false+ to halt

Returns:

  • (Object)

    the fully-accumulated response body



147
148
149
150
151
152
153
154
155
156
157
158
159
# File 'lib/toc_doc/core/connection.rb', line 147

def paginate(path, options = {}, &)
  data = get(path, options)
  return data unless block_given?

  loop do
    next_options = yield(data, last_response)
    break unless next_options

    get(path, next_options)
  end

  data
end