Class: Marvel::JsonParser

Inherits:
Faraday::Response::Middleware
  • Object
show all
Defined in:
lib/marvel/middleware.rb

Instance Method Summary collapse

Instance Method Details

#on_complete(env) ⇒ Object



9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
# File 'lib/marvel/middleware.rb', line 9

def on_complete(env)
  json = JSON.parse(env[:body], :symbolize_names => true)
  if json[:code] == 200
    json = json[:data][:results] || json[:data][:result]
    json.each do |j|
      j[:characters] = j[:characters][:items] if j[:characters].present?
      j[:comics]     = j[:comics][:items]     if j[:comics].present?
      j[:creators]   = j[:creators][:items]   if j[:creators].present?
      j[:events]     = j[:events][:items]     if j[:events].present?
      j[:series]     = j[:series][:items]     if j[:series].present?
      j[:stories]    = j[:stories][:items]    if j[:stories].present?
    end
    # TODO: We don't *alwyas* want to do this
    json = json.first if json.length == 1
    errors = json.delete(:errors) || {}
     = json.delete(:metadata) || []
    env[:body] = { :data => json, :errors => errors, :metadata =>  }
  else
    # TODO: Raise an error
    env[:body] = { :data => json, :errors => json[:status], :metadata =>  }
  end
end