Sha256: 8d2d7d4b40a962420e722d0fe5a8584f744bddcbda001425fa9f2d380ba8573f

Contents?: true

Size: 1.2 KB

Versions: 16

Compression:

Stored size: 1.2 KB

Contents

require 'faraday'



module Saddle
  module Middleware
    module Response

    # Public: Parse response bodies as JSON.
      class ParseJson < Faraday::Middleware
        CONTENT_TYPE = 'Content-Type'.freeze
        MIME_TYPE    = 'application/json'.freeze

        dependency do
          require 'json' unless defined?(::JSON)
        end

        def call(env)
          result = @app.call env
          if parse_response?(env)
            # Make sure we're working with a valid body that's not a String
            if env[:body] && env[:body].respond_to?(:to_str)
              env[:request_headers][CONTENT_TYPE] ||= MIME_TYPE
              env[:body] = ::JSON.parse env[:body]
            end
          end
          result
        end

        def parse_response?(env)
          has_body?(env) and (response_type(env) == MIME_TYPE)
        end

        def has_body?(env)
          body = env[:body] and !(body.respond_to?(:to_str) and body.empty?)
        end

        def response_type(env)
          return nil unless env[:response_headers]
          type = env[:response_headers][CONTENT_TYPE].to_s
          type = type.split(';', 2).first if type.index(';')
          type
        end
      end

    end
  end
end

Version data entries

16 entries across 16 versions & 1 rubygems

Version Path
saddle-0.0.33 lib/saddle/middleware/response/parse_json.rb
saddle-0.0.32 lib/saddle/middleware/response/parse_json.rb
saddle-0.0.31 lib/saddle/middleware/response/parse_json.rb
saddle-0.0.30 lib/saddle/middleware/response/parse_json.rb
saddle-0.0.27 lib/saddle/middleware/response/parse_json.rb
saddle-0.0.26 lib/saddle/middleware/response/parse_json.rb
saddle-0.0.25 lib/saddle/middleware/response/parse_json.rb
saddle-0.0.23 lib/saddle/middleware/response/parse_json.rb
saddle-0.0.22 lib/saddle/middleware/response/parse_json.rb
saddle-0.0.21 lib/saddle/middleware/response/parse_json.rb
saddle-0.0.19 lib/saddle/middleware/response/parse_json.rb
saddle-0.0.18 lib/saddle/middleware/response/parse_json.rb
saddle-0.0.17 lib/saddle/middleware/response/parse_json.rb
saddle-0.0.16 lib/saddle/middleware/response/parse_json.rb
saddle-0.0.15 lib/saddle/middleware/response/parse_json.rb
saddle-0.0.14 lib/saddle/middleware/response/parse_json.rb