class Johac::Response

Attributes

body[R]
chain[R]
exception[R]
response[R]
status[R]

Public Class Methods

new(result, chain=[]) click to toggle source
# File lib/johac/response.rb, line 6
def initialize(result, chain=[])
  if result.kind_of?(Faraday::Response)
    @response = result
  else
    @exception = result
  end

  @body = result.body if result.respond_to?(:body)
  @status = result.status if result.respond_to?(:status)
  @chain = chain
end

Public Instance Methods

and_then(&block) click to toggle source

@see flat_map

# File lib/johac/response.rb, line 98
def and_then(&block)
  flat_map(&block)
end
code() click to toggle source

HTTP Status code

@return response status code

# File lib/johac/response.rb, line 28
def code
  status
end
dig(*args) click to toggle source

Dig for a item in the body

@param args [Varargs] path of value

@see {Hash.dig}

@return value of key path

# File lib/johac/response.rb, line 68
def dig(*args)
  body.kind_of?(Hash) ? body.dig(*args) : nil
end
error?() click to toggle source

Determine if the request failed

@return true if response failed (http or expcetion)

# File lib/johac/response.rb, line 21
def error?
  status.nil? || status >= 400
end
flat_map() { |self, chain| ... } click to toggle source

Chain another request to the successful response. The expected output of the block is another Johac::Response object.

This enables request chaining, where an error in the chain will prevent further processing and return an error response

response = client.request1(param)

.flat_map { |r| client.request2(r.object.value) }
.flat_map { |r| client.request3(r.object.value) }

@param block [Block] to invoke

# File lib/johac/response.rb, line 83
def flat_map(&block)
  if response?
    begin
      result = yield self, chain
      result.set_chain(chain + [self])
      result
    rescue => e
      Response.new(e, chain + [self])
    end
  else
    self
  end
end
map() { |body| ... } click to toggle source

Map response body if successful

@param block [Block] mapping function block

@return result of block

# File lib/johac/response.rb, line 42
def map(&block)
  unless error?
    yield body
  else
    nil
  end
end
map_error() { |exception| ... } click to toggle source

Map the exception if present

@param block [Block] to invoke

# File lib/johac/response.rb, line 53
def map_error(&block)
  if error?
    yield exception
  else
    nil
  end
end
object() click to toggle source

@return OpenStruct object of hash, or empty struct if error

# File lib/johac/response.rb, line 33
def object
  error? ? OpenStruct.new : OpenStruct.new(body)
end

Protected Instance Methods

response?() click to toggle source
# File lib/johac/response.rb, line 108
def response?
  response != nil
end
set_chain(chain) click to toggle source
# File lib/johac/response.rb, line 104
def set_chain(chain)
  @chain = chain
end