Sha256: ca7ffc703a44e6de4bbc91987129405a5473b58feb92bdff2f55c1cea026aba1

Contents?: true

Size: 1.34 KB

Versions: 11

Compression:

Stored size: 1.34 KB

Contents

require 'footrest/response_middleware'

module Footrest
  # Public: Parse response bodies as JSON.
  class ParseJson < ResponseMiddleware
    dependency do
      require 'json' unless defined?(::JSON)
    end

    define_parser do |body|
      ::JSON.parse body unless body.strip.empty?
    end

    # 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

Version data entries

11 entries across 11 versions & 1 rubygems

Version Path
footrest-0.5.8 lib/footrest/parse_json.rb
footrest-0.5.7 lib/footrest/parse_json.rb
footrest-0.5.6 lib/footrest/parse_json.rb
footrest-0.5.5 lib/footrest/parse_json.rb
footrest-0.5.3 lib/footrest/parse_json.rb
footrest-0.5.2 lib/footrest/parse_json.rb
footrest-0.5.1 lib/footrest/parse_json.rb
footrest-0.5.0 lib/footrest/parse_json.rb
footrest-0.4.1 lib/footrest/parse_json.rb
footrest-0.3.1 lib/footrest/parse_json.rb
footrest-0.3.0 lib/footrest/parse_json.rb