Sha256: 1625c7b36dd7d4074d321d51ea32a02c9f10f06fcbceb1bbeb0f8988ff9cc78f

Contents?: true

Size: 1.12 KB

Versions: 4

Compression:

Stored size: 1.12 KB

Contents

require 'faraday'



module Saddle::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

Version data entries

4 entries across 4 versions & 1 rubygems

Version Path
saddle-0.0.12 lib/saddle/middleware/response/parse_json.rb
saddle-0.0.11 lib/saddle/middleware/response/parse_json.rb
saddle-0.0.10 lib/saddle/middleware/response/parse_json.rb
saddle-0.0.7 lib/saddle/middleware/response/parse_json.rb