Class: Increase::Middleware::EncodeJson
- Inherits:
-
Faraday::Middleware
- Object
- Faraday::Middleware
- Increase::Middleware::EncodeJson
- Defined in:
- lib/increase/middleware/encode_json.rb
Overview
JSON request middleware for Faraday 1.0 In Faraday 2.0, the JSON middleware is bundled with the Faraday gem itself
This middleware is from github.com/lostisland/faraday_middleware/blob/main/lib/faraday_middleware/request/encode_json.rb
Constant Summary collapse
- CONTENT_TYPE =
"Content-Type"
- MIME_TYPE =
"application/json"
- MIME_TYPE_REGEX =
%r{^application/(vnd\..+\+)?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
21 22 23 24 25 26 |
# File 'lib/increase/middleware/encode_json.rb', line 21 def call(env) match_content_type(env) do |data| env[:body] = encode data end @app.call env end |
#encode(data) ⇒ Object
28 29 30 |
# File 'lib/increase/middleware/encode_json.rb', line 28 def encode(data) ::JSON.generate data end |
#has_body?(env) ⇒ Boolean
44 45 46 |
# File 'lib/increase/middleware/encode_json.rb', line 44 def has_body?(env) (body = env[:body]) && !(body.respond_to?(:to_str) && body.empty?) end |
#match_content_type(env) {|| ... } ⇒ Object
32 33 34 35 36 37 |
# File 'lib/increase/middleware/encode_json.rb', line 32 def match_content_type(env) return unless process_request?(env) env[:request_headers][CONTENT_TYPE] ||= MIME_TYPE yield env[:body] unless env[:body].respond_to?(:to_str) end |
#process_request?(env) ⇒ Boolean
39 40 41 42 |
# File 'lib/increase/middleware/encode_json.rb', line 39 def process_request?(env) type = request_type(env) has_body?(env) && (type.empty? || MIME_TYPE_REGEX =~ type) end |
#request_type(env) ⇒ Object
48 49 50 51 52 |
# File 'lib/increase/middleware/encode_json.rb', line 48 def request_type(env) type = env[:request_headers][CONTENT_TYPE].to_s type = type.split(";", 2).first if type.index(";") type end |