Class: Quandl::Client::Middleware::ParseJSON

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

Instance Method Summary collapse

Instance Method Details

#format_collection(json, env) ⇒ Object



39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
# File 'lib/quandl/client/middleware/parse_json.rb', line 39

def format_collection(json, env)
  errors = json.delete(:errors) || {}
   = json.delete(:metadata) || {}
  docs = json.delete(:docs)
  # collect some response data
  .merge!(json).merge!({
    status:                 env[:status],
    headers:                env[:response_headers],
    })
  # return object
  object = {
    :data => docs,
    :errors => errors,
    :metadata => 
  }
  env[:status] = 200
  object
end

#format_record(json, env) ⇒ Object



21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# File 'lib/quandl/client/middleware/parse_json.rb', line 21

def format_record(json, env)
  errors = json.delete(:errors) || {}
   = json.delete(:metadata) || {}
  # collect some response data
  .merge!({
    status:                 env[:status],
    headers:                env[:response_headers],
    })
  # return object
  object = {
    :data => json,
    :errors => errors,
    :metadata => 
  }
  env[:status] = 200
  object
end

#on_complete(env) ⇒ Object



7
8
9
10
11
12
13
14
# File 'lib/quandl/client/middleware/parse_json.rb', line 7

def on_complete(env)
  env[:body] = case env[:status]
  when 204
    parse('{}', env)
  else
    parse(env[:body], env)
  end
end

#parse(body, env) ⇒ Object



16
17
18
19
# File 'lib/quandl/client/middleware/parse_json.rb', line 16

def parse(body, env)
  json = parse_json(body, env)
  json.has_key?(:docs) ? format_collection( json, env ) : format_record( json, env )
end

#parse_json(body = nil, env) ⇒ Object



58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
# File 'lib/quandl/client/middleware/parse_json.rb', line 58

def parse_json(body = nil, env)
  body ||= '{}'
  json = begin
    Yajl.load(body, :symbolize_keys => true)
  rescue Yajl::ParseError
    nil
  end
  # invalid json body?
  if json.blank?
    # fallback to error message
    json = { 
      id: 1, 
      errors: {
        parse_error:  "Quandl::Client::ParseJSON error. status: #{env[:status]}, body: #{body.inspect}"
      }
    }
  end
  json
end