Class: ApiTransformer::BackendResponse

Inherits:
Object
  • Object
show all
Defined in:
lib/api_transformer/backend_response.rb

Overview

Container for backend response data

Defined Under Namespace

Classes: Data

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(http) ⇒ BackendResponse

Returns a new instance of BackendResponse.



14
15
16
17
18
19
# File 'lib/api_transformer/backend_response.rb', line 14

def initialize(http)
  @http = http
  @body = ""

  @http.stream { |chunk| @body += chunk }
end

Instance Attribute Details

#bodyObject (readonly)

Returns the value of attribute body.



12
13
14
# File 'lib/api_transformer/backend_response.rb', line 12

def body
  @body
end

Instance Method Details

#[](key) ⇒ Object



43
44
45
46
47
48
49
# File 'lib/api_transformer/backend_response.rb', line 43

def [](key)
  if json.respond_to?(:keys)
    json[key]
  else
    nil
  end
end

#content_typeObject



61
62
63
# File 'lib/api_transformer/backend_response.rb', line 61

def content_type
  @http.response_header["CONTENT_TYPE"]
end

#cookiesObject



51
52
53
54
55
56
57
58
59
# File 'lib/api_transformer/backend_response.rb', line 51

def cookies
  pairs = @http.response_header["SET_COOKIE"].split("\s*;\s*")
  data = pairs.reduce({}) do |hash, pair|
    key, value = pair.split("=")
    hash.merge(key => value)
  end

  Data.try_convert(data)
end

#headersObject



65
66
67
# File 'lib/api_transformer/backend_response.rb', line 65

def headers
  @http.response_header
end

#jsonObject



29
30
31
32
33
34
35
36
37
38
39
40
41
# File 'lib/api_transformer/backend_response.rb', line 29

def json
  @data ||= begin
    json = JSON.parse(@body)

    if json.respond_to?(:keys)
      Data.try_convert(json)
    else
      json
    end
  end
rescue JSON::ParserError, Encoding::InvalidByteSequenceError
  {}
end

#statusObject



25
26
27
# File 'lib/api_transformer/backend_response.rb', line 25

def status
  @http.response_header.http_status
end

#stream(&block) ⇒ Object



69
70
71
72
73
74
75
76
77
78
79
80
# File 'lib/api_transformer/backend_response.rb', line 69

def stream(&block)
  if block
    block.call(@body)

    @http.stream(&block)
    EM::Synchrony::Iterator.new([block]).each do |_, iter|
      @http.callback { iter.next }
    end
  else
    fail "a block is required when streaming"
  end
end

#success?Boolean

Returns:

  • (Boolean)


21
22
23
# File 'lib/api_transformer/backend_response.rb', line 21

def success?
  status >= 200 && status < 300
end