Class: BitBucket::Request::Jsonize

Inherits:
Faraday::Middleware
  • Object
show all
Defined in:
lib/bitbucket_rest_api/request/jsonize.rb

Constant Summary collapse

CONTENT_TYPE =
'Content-Type'
MIME_TYPE =
'application/json'

Instance Method Summary collapse

Instance Method Details

#call(env) ⇒ Object



11
12
13
14
15
16
17
# File 'lib/bitbucket_rest_api/request/jsonize.rb', line 11

def call(env)
  if request_with_body?(env)
    env[:request_headers][CONTENT_TYPE] ||= MIME_TYPE
    env[:body] = encode_body env unless env[:body].respond_to?(:to_str)
  end
  @app.call env
end

#encode_body(env) ⇒ Object



19
20
21
# File 'lib/bitbucket_rest_api/request/jsonize.rb', line 19

def encode_body(env)
  MultiJson.dump(env[:body])
end

#has_body?(env) ⇒ Boolean

Don’t encode bodies in string form

Returns:

  • (Boolean)


29
30
31
# File 'lib/bitbucket_rest_api/request/jsonize.rb', line 29

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

#request_type(env) ⇒ Object



33
34
35
36
37
# File 'lib/bitbucket_rest_api/request/jsonize.rb', line 33

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

#request_with_body?(env) ⇒ Boolean

Returns:

  • (Boolean)


23
24
25
26
# File 'lib/bitbucket_rest_api/request/jsonize.rb', line 23

def request_with_body?(env)
  type = request_type(env)
  has_body?(env) && (type.empty? || (type == MIME_TYPE))
end