Class: ElastomerClient::Middleware::ParseJson
- Inherits:
-
Faraday::Middleware
- Object
- Faraday::Middleware
- ElastomerClient::Middleware::ParseJson
- Defined in:
- lib/elastomer_client/middleware/parse_json.rb
Overview
Parse response bodies as JSON.
Constant Summary collapse
- CONTENT_TYPE =
"Content-Type".freeze
- MIME_TYPE =
"application/json".freeze
Instance Method Summary collapse
- #call(environment) ⇒ Object
-
#parse(body) ⇒ Object
Parse the response body.
- #process_response?(env) ⇒ Boolean
- #response_type(env) ⇒ Object
Instance Method Details
#call(environment) ⇒ Object
11 12 13 14 15 16 17 |
# File 'lib/elastomer_client/middleware/parse_json.rb', line 11 def call(environment) @app.call(environment).on_complete do |env| if process_response?(env) env[:body] = parse env[:body] end end end |
#parse(body) ⇒ Object
Parse the response body.
20 21 22 23 24 |
# File 'lib/elastomer_client/middleware/parse_json.rb', line 20 def parse(body) MultiJson.load(body) if body.respond_to?(:to_str) && !body.strip.empty? rescue StandardError, SyntaxError => e raise Faraday::ParsingError, e end |
#process_response?(env) ⇒ Boolean
26 27 28 29 |
# File 'lib/elastomer_client/middleware/parse_json.rb', line 26 def process_response?(env) type = response_type(env) type.empty? || type == MIME_TYPE end |
#response_type(env) ⇒ Object
31 32 33 34 35 |
# File 'lib/elastomer_client/middleware/parse_json.rb', line 31 def response_type(env) type = env[:response_headers][CONTENT_TYPE].to_s type = type.split(";", 2).first if type.index(";") type end |