Sha256: 42cbf853d5b8766eb997f2ad66215007d7a29877542ce2fe934c1d1f3564fc73

Contents?: true

Size: 1.13 KB

Versions: 17

Compression:

Stored size: 1.13 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?(result)
            result.env[:body] = ::JSON.parse(result.env[:body])
          end
          result
        end


        private

        def parse_response?(result)
          has_body?(result) && (response_type(result) == MIME_TYPE)
        end

        def has_body?(result)
          result.env[:body] &&
            (!result.env[:body].respond_to?(:to_str) || # must already be in string format
             !result.env[:body].empty?) # or must be non-empty
        end

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

      end

    end
  end
end

Version data entries

17 entries across 17 versions & 1 rubygems

Version Path
saddle-0.1.0 lib/saddle/middleware/response/parse_json.rb
saddle-0.0.53 lib/saddle/middleware/response/parse_json.rb
saddle-0.0.51 lib/saddle/middleware/response/parse_json.rb
saddle-0.0.50 lib/saddle/middleware/response/parse_json.rb
saddle-0.0.49 lib/saddle/middleware/response/parse_json.rb
saddle-0.0.48 lib/saddle/middleware/response/parse_json.rb
saddle-0.0.46 lib/saddle/middleware/response/parse_json.rb
saddle-0.0.45 lib/saddle/middleware/response/parse_json.rb
saddle-0.0.44 lib/saddle/middleware/response/parse_json.rb
saddle-0.0.43 lib/saddle/middleware/response/parse_json.rb
saddle-0.0.42 lib/saddle/middleware/response/parse_json.rb
saddle-0.0.41 lib/saddle/middleware/response/parse_json.rb
saddle-0.0.38 lib/saddle/middleware/response/parse_json.rb
saddle-0.0.37 lib/saddle/middleware/response/parse_json.rb
saddle-0.0.36 lib/saddle/middleware/response/parse_json.rb
saddle-0.0.35 lib/saddle/middleware/response/parse_json.rb
saddle-0.0.34 lib/saddle/middleware/response/parse_json.rb