Sha256: 06d3f94c0954a1918538d0b86c42a8b1e3f2408ff28c6b2b30b51e64a85331e9

Contents?: true

Size: 1.13 KB

Versions: 10

Compression:

Stored size: 1.13 KB

Contents

module Quandl
module Client
module Middleware

class ParseJSON < Faraday::Response::Middleware

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

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

  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

end

end
end
end

Version data entries

10 entries across 10 versions & 1 rubygems

Version Path
quandl_client-2.1.4 lib/quandl/client/middleware/parse_json.rb
quandl_client-2.1.3 lib/quandl/client/middleware/parse_json.rb
quandl_client-2.1.2 lib/quandl/client/middleware/parse_json.rb
quandl_client-2.1.1 lib/quandl/client/middleware/parse_json.rb
quandl_client-2.1.0 lib/quandl/client/middleware/parse_json.rb
quandl_client-2.0.1 lib/quandl/client/middleware/parse_json.rb
quandl_client-2.0.0 lib/quandl/client/middleware/parse_json.rb
quandl_client-0.1.17 lib/quandl/client/middleware/parse_json.rb
quandl_client-0.1.16 lib/quandl/client/middleware/parse_json.rb
quandl_client-0.1.15 lib/quandl/client/middleware/parse_json.rb