Class: ElastomerClient::Middleware::EncodeJson
- Inherits:
-
Faraday::Middleware
- Object
- Faraday::Middleware
- ElastomerClient::Middleware::EncodeJson
- Defined in:
- lib/elastomer_client/middleware/encode_json.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
- #add_content_type!(env) ⇒ Object
- #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
#add_content_type!(env) ⇒ Object
49 50 51 52 53 54 |
# File 'lib/elastomer_client/middleware/encode_json.rb', line 49 def add_content_type!(env) method = env[:method] if method == :put || method == :post || has_body?(env) env[:request_headers][CONTENT_TYPE] ||= MIME_TYPE end end |
#call(env) ⇒ Object
16 17 18 19 20 21 |
# File 'lib/elastomer_client/middleware/encode_json.rb', line 16 def call(env) match_content_type(env) do |data| env[:body] = encode data end @app.call env end |
#encode(data) ⇒ Object
23 24 25 |
# File 'lib/elastomer_client/middleware/encode_json.rb', line 23 def encode(data) MultiJson.dump data end |
#has_body?(env) ⇒ Boolean
39 40 41 |
# File 'lib/elastomer_client/middleware/encode_json.rb', line 39 def has_body?(env) (body = env[:body]) && !(body.respond_to?(:to_str) && body.empty?) end |
#match_content_type(env) ⇒ Object
27 28 29 30 31 32 |
# File 'lib/elastomer_client/middleware/encode_json.rb', line 27 def match_content_type(env) add_content_type!(env) if process_request?(env) yield env[:body] unless env[:body].respond_to?(:to_str) end end |
#process_request?(env) ⇒ Boolean
34 35 36 37 |
# File 'lib/elastomer_client/middleware/encode_json.rb', line 34 def process_request?(env) type = request_type(env) has_body?(env) && (type.empty? || type == MIME_TYPE) end |
#request_type(env) ⇒ Object
43 44 45 46 47 |
# File 'lib/elastomer_client/middleware/encode_json.rb', line 43 def request_type(env) type = env[:request_headers][CONTENT_TYPE].to_s type = type.split(";", 2).first if type.index(";") type end |