Class: FaradayMiddleware::ParseJson::MimeTypeFix
- Inherits:
-
ResponseMiddleware
- Object
- Faraday::Middleware
- ResponseMiddleware
- FaradayMiddleware::ParseJson::MimeTypeFix
- Defined in:
- lib/faraday_middleware/response/parse_json.rb
Overview
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”.
Constant Summary collapse
- MIME_TYPE =
'application/json'
- BRACKETS =
%w-[ {-.freeze
- WHITESPACE =
[' ', "\n", "\r", "\t"].freeze
Constants inherited from ResponseMiddleware
ResponseMiddleware::CONTENT_TYPE
Instance Method Summary collapse
Methods inherited from ResponseMiddleware
#call, define_parser, inherited, #initialize, #parse, #preserve_raw?, #process_response_type?, #response_type
Constructor Details
This class inherits a constructor from FaradayMiddleware::ResponseMiddleware
Instance Method Details
#first_char(body) ⇒ Object
39 40 41 42 43 44 |
# File 'lib/faraday_middleware/response/parse_json.rb', line 39 def first_char(body) idx = -1 char = body[idx += 1] char = body[idx += 1] while char && WHITESPACE.include?(char) char end |
#parse_response?(env) ⇒ Boolean
35 36 37 |
# File 'lib/faraday_middleware/response/parse_json.rb', line 35 def parse_response?(env) super && BRACKETS.include?(first_char(env[:body])) end |
#process_response(env) ⇒ Object
25 26 27 28 29 30 |
# File 'lib/faraday_middleware/response/parse_json.rb', line 25 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 |