Class: Storenvy::EncodeOj
- Inherits:
-
Faraday::Middleware
- Object
- Faraday::Middleware
- Storenvy::EncodeOj
- Defined in:
- lib/storenvy/core/response_parser.rb
Overview
Request middleware that encodes the body as JSON.
Processes only requests with matching Content-type or those without a type. If a request doesn’t have a type but has a body, it sets the Content-type to JSON MIME-type.
Doesn’t try to encode bodies that already are in string form.
Constant Summary collapse
- CONTENT_TYPE =
'Content-Type'.freeze
- MIME_TYPE =
'application/json'.freeze
Instance Method Summary collapse
- #call(env) ⇒ Object
- #encode(data) ⇒ Object
- #has_body?(env) ⇒ Boolean
- #match_content_type(env) ⇒ Object
- #process_request?(env) ⇒ Boolean
- #request_type(env) ⇒ Object
Instance Method Details
#call(env) ⇒ Object
48 49 50 51 52 53 |
# File 'lib/storenvy/core/response_parser.rb', line 48 def call(env) match_content_type(env) do |data| env[:body] = encode data end @app.call env end |
#encode(data) ⇒ Object
55 56 57 |
# File 'lib/storenvy/core/response_parser.rb', line 55 def encode(data) ::Oj.dump data end |
#has_body?(env) ⇒ Boolean
71 72 73 |
# File 'lib/storenvy/core/response_parser.rb', line 71 def has_body?(env) body = env[:body] and !(body.respond_to?(:to_str) and body.empty?) end |
#match_content_type(env) ⇒ Object
59 60 61 62 63 64 |
# File 'lib/storenvy/core/response_parser.rb', line 59 def match_content_type(env) if process_request?(env) env[:request_headers][CONTENT_TYPE] ||= MIME_TYPE yield env[:body] unless env[:body].respond_to?(:to_str) end end |
#process_request?(env) ⇒ Boolean
66 67 68 69 |
# File 'lib/storenvy/core/response_parser.rb', line 66 def process_request?(env) type = request_type(env) has_body?(env) and (type.empty? or type == MIME_TYPE) end |
#request_type(env) ⇒ Object
75 76 77 78 79 |
# File 'lib/storenvy/core/response_parser.rb', line 75 def request_type(env) type = env[:request_headers][CONTENT_TYPE].to_s type = type.split(';', 2).first if type.index(';') type end |