Sha256: 1ffb88e88875fd93a14c34a0e4b12ce6b91b4b68b6f31a8a65418ccf93d47a46

Contents?: true

Size: 793 Bytes

Versions: 2

Compression:

Stored size: 793 Bytes

Contents

require "faraday"
require "multi_json"

module Zaikio::Client::Helpers
  class JSONParser < Faraday::Response::Middleware
    def on_complete(env)
      connection_error(env) unless /^(2\d\d)|422|404$/.match?(env.status.to_s)

      raise Spyke::ResourceNotFound if env.status.to_s == "404"

      env.body = parse_body(env.body)
    end

    def connection_error(env)
      raise Spyke::ConnectionError, "Status: #{env.status}, URL: #{env.url}, body: #{env.body}"
    end

    def parse_body(body)
      json = MultiJson.load(body, symbolize_keys: true)
      {
        data: json,
        metadata: {},
        errors: json.is_a?(Hash) ? json[:errors] : {}
      }
    rescue MultiJson::ParseError
      {
        data: {},
        metadata: {},
        errors: {}
      }
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
zaikio-client-helpers-0.1.1 lib/zaikio/client/helpers/json_parser.rb
zaikio-client-helpers-0.1.0 lib/zaikio/client/helpers/json_parser.rb