Sha256: 6e32619c63b0e47109c55e477192b7de28c91e1ab10b933d5ffca622b822a260

Contents?: true

Size: 1.38 KB

Versions: 2

Compression:

Stored size: 1.38 KB

Contents

require 'faraday_middleware/response_middleware'

module FaradayMiddleware
  # Public: Parse response bodies as JSON.
  class ParseJson < ResponseMiddleware
    dependency 'json'

    define_parser { |body|
      JSON.parse body unless body.empty?
    }

    # Public: Override the content-type of the response with "application/json"
    # if the response body looks like it might be JSON, i.e. starts with an
    # open bracket.
    #
    # This is to fix responses from certain API providers that insist on serving
    # JSON with wrong MIME-types such as "text/javascript".
    class MimeTypeFix < ResponseMiddleware
      MIME_TYPE = 'application/json'.freeze

      def process_response(env)
        old_type = env[:response_headers][CONTENT_TYPE].to_s
        new_type = MIME_TYPE.dup
        new_type << ';' << old_type.split(';', 2).last if old_type.index(';')
        env[:response_headers][CONTENT_TYPE] = new_type
      end

      BRACKETS = %w- [ { -
      WHITESPACE = [ " ", "\n", "\r", "\t" ]

      def parse_response?(env)
        super and BRACKETS.include? first_char(env[:body])
      end

      def first_char(body)
        idx = -1
        begin
          char = body[idx += 1]
          char = char.chr if char
        end while char and WHITESPACE.include? char
        char
      end
    end
  end
end

# deprecated alias
Faraday::Response::ParseJson = FaradayMiddleware::ParseJson

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
faraday_middleware-0.8.6 lib/faraday_middleware/response/parse_json.rb
faraday_middleware-0.8.5 lib/faraday_middleware/response/parse_json.rb