Class: Quandl::Client::Middleware::ParseJSON
- Inherits:
-
Faraday::Response::Middleware
- Object
- Faraday::Response::Middleware
- Quandl::Client::Middleware::ParseJSON
- Defined in:
- lib/quandl/client/middleware/parse_json.rb
Instance Method Summary collapse
- #format_collection(json, env) ⇒ Object
- #format_record(json, env) ⇒ Object
- #on_complete(env) ⇒ Object
- #parse(body, env) ⇒ Object
- #parse_json(body = nil, env) ⇒ Object
Instance Method Details
#format_collection(json, env) ⇒ Object
41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 |
# File 'lib/quandl/client/middleware/parse_json.rb', line 41 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], method: env[:method], }) # each doc metadata references metadata docs.each{|d| d[:metadata] = } # return object object = { :data => docs, :errors => errors, :metadata => } env[:status] = 200 object end |
#format_record(json, env) ⇒ Object
22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 |
# File 'lib/quandl/client/middleware/parse_json.rb', line 22 def format_record(json, env) errors = json.delete(:errors) || {} = json.delete(:metadata) || {} # collect some response data .merge!({ status: env[:status], headers: env[:response_headers], method: env[:method], }) # return object object = { :data => json, :errors => errors, :metadata => } env[:status] = 200 object end |
#on_complete(env) ⇒ Object
8 9 10 11 12 13 14 15 |
# File 'lib/quandl/client/middleware/parse_json.rb', line 8 def on_complete(env) env[:body] = case env[:status] when 204 parse('{}', env) else parse(env[:body], env) end end |
#parse(body, env) ⇒ Object
17 18 19 20 |
# File 'lib/quandl/client/middleware/parse_json.rb', line 17 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
63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 |
# File 'lib/quandl/client/middleware/parse_json.rb', line 63 def parse_json(body = nil, env) body ||= '{}' json = begin JSON.parse(body).symbolize_keys! rescue JSON::ParserError nil end # invalid json body? if json.blank? # fallback to error message json = { id: 1, errors: { parse_errors: [ "Quandl::Client::ParseJSON error. status: #{env[:status]}, body: #{body.inspect}" ] } } end json end |