Class: Saddle::Middleware::Response::ParseJson
- Inherits:
-
Faraday::Middleware
- Object
- Faraday::Middleware
- Saddle::Middleware::Response::ParseJson
- Defined in:
- lib/saddle/middleware/response/parse_json.rb
Overview
Public: Parse response bodies as JSON.
Constant Summary collapse
- CONTENT_TYPE =
'Content-Type'.freeze
- MIME_TYPE =
'application/json'.freeze
Instance Method Summary collapse
- #call(env) ⇒ Object
- #has_body?(env) ⇒ Boolean
- #parse_response?(env) ⇒ Boolean
- #response_type(env) ⇒ Object
Instance Method Details
#call(env) ⇒ Object
17 18 19 20 21 22 23 24 25 26 |
# File 'lib/saddle/middleware/response/parse_json.rb', line 17 def call(env) if parse_response?(env) # Make sure we're working with a valid body that's not a String if env.body and !env.body.respond_to?(:to_str) env[:request_headers][CONTENT_TYPE] ||= MIME_TYPE env.body = ::JSON.dump env.body end end @app.call env end |
#has_body?(env) ⇒ Boolean
32 33 34 |
# File 'lib/saddle/middleware/response/parse_json.rb', line 32 def has_body?(env) body = env[:body] and !(body.respond_to?(:to_str) and body.empty?) end |
#parse_response?(env) ⇒ Boolean
28 29 30 |
# File 'lib/saddle/middleware/response/parse_json.rb', line 28 def parse_response?(env) has_body?(env) and (response_type(env) == MIME_TYPE) end |
#response_type(env) ⇒ Object
36 37 38 39 40 41 |
# File 'lib/saddle/middleware/response/parse_json.rb', line 36 def response_type(env) return nil unless env[:response_headers] type = env[:response_headers][CONTENT_TYPE].to_s type = type.split(';', 2).first if type.index(';') type end |