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'.freeze
MIME_TYPE =
'application/json'.freeze

Instance Method Summary collapse

Instance Method Details

#call(env) ⇒ Object



13
14
15
16
17
18
19
20
21
22
23
24
# File 'lib/bitbucket_rest_api/request/jsonize.rb', line 13

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)
  else
    # Ensure valid body for put and post requests
    if [:put, :patch, :post].include? env[:method]
      env[:body] = encode_body({})
    end
  end
  @app.call env
end

#encode_body(env) ⇒ Object



26
27
28
29
30
31
32
# File 'lib/bitbucket_rest_api/request/jsonize.rb', line 26

def encode_body(env)
  if MultiJson.respond_to?(:dump)
    MultiJson.dump env[:body]
  else
    MultiJson.encode env[:body]
  end
end

#has_body?(env) ⇒ Boolean

Don’t encode bodies in string form

Returns:

  • (Boolean)


40
41
42
# File 'lib/bitbucket_rest_api/request/jsonize.rb', line 40

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

#request_type(env) ⇒ Object



44
45
46
47
48
# File 'lib/bitbucket_rest_api/request/jsonize.rb', line 44

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)


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

def request_with_body?(env)
  type = request_type(env)
  has_body?(env) and (type.empty? or type == MIME_TYPE)
end