Class: Elastomer::Middleware::ParseJson

Inherits:
Faraday::Middleware
  • Object
show all
Defined in:
lib/elastomer/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

Instance Method Details

#call(environment) ⇒ Object



9
10
11
12
13
14
15
# File 'lib/elastomer/middleware/parse_json.rb', line 9

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.



18
19
20
21
22
# File 'lib/elastomer/middleware/parse_json.rb', line 18

def parse(body)
  MultiJson.load(body) if body.respond_to?(:to_str) && !body.strip.empty?
rescue StandardError, SyntaxError => e
  raise Faraday::Error::ParsingError, e
end

#process_response?(env) ⇒ Boolean

Returns:

  • (Boolean)


24
25
26
27
# File 'lib/elastomer/middleware/parse_json.rb', line 24

def process_response?(env)
  type = response_type(env)
  type.empty? || type == MIME_TYPE
end

#response_type(env) ⇒ Object



29
30
31
32
33
# File 'lib/elastomer/middleware/parse_json.rb', line 29

def response_type(env)
  type = env[:response_headers][CONTENT_TYPE].to_s
  type = type.split(";", 2).first if type.index(";")
  type
end