Class: FaradayMiddleware::EncodeJson

Inherits:
Faraday::Middleware
  • Object
show all
Defined in:
lib/faraday_middleware/request/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'
MIME_TYPE =
'application/json'
MIME_TYPE_REGEX =
%r{^application/(vnd\..+\+)?json$}.freeze

Instance Method Summary collapse

Instance Method Details

#call(env) ⇒ Object



22
23
24
25
26
27
# File 'lib/faraday_middleware/request/encode_json.rb', line 22

def call(env)
  match_content_type(env) do |data|
    env[:body] = encode data
  end
  @app.call env
end

#encode(data) ⇒ Object



29
30
31
# File 'lib/faraday_middleware/request/encode_json.rb', line 29

def encode(data)
  ::JSON.generate data
end

#has_body?(env) ⇒ Boolean

Returns:

  • (Boolean)


45
46
47
# File 'lib/faraday_middleware/request/encode_json.rb', line 45

def has_body?(env)
  (body = env[:body]) && !(body.respond_to?(:to_str) && body.empty?)
end

#match_content_type(env) {|| ... } ⇒ Object

Yields:

  • ()


33
34
35
36
37
38
# File 'lib/faraday_middleware/request/encode_json.rb', line 33

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

Returns:

  • (Boolean)


40
41
42
43
# File 'lib/faraday_middleware/request/encode_json.rb', line 40

def process_request?(env)
  type = request_type(env)
  has_body?(env) && (type.empty? || MIME_TYPE_REGEX =~ type)
end

#request_type(env) ⇒ Object



49
50
51
52
53
# File 'lib/faraday_middleware/request/encode_json.rb', line 49

def request_type(env)
  type = env[:request_headers][CONTENT_TYPE].to_s
  type = type.split(';', 2).first if type.index(';')
  type
end