Sha256: 6a314d43a0a86ea53dd5a7488ccccab747f68cfb7d5bfa4832909fce8f134a73

Contents?: true

Size: 1.22 KB

Versions: 5

Compression:

Stored size: 1.22 KB

Contents

# encoding: utf-8

require 'faraday'

module BitBucket
  class Request::Jsonize < Faraday::Middleware

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

    dependency 'multi_json'

    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

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

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

    # Don't encode bodies in string form
    def has_body?(env)
      body = env[:body] and !(body.respond_to?(:to_str) and body.empty?)
    end

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

  end # Request::Jsonize
end # BitBucket

Version data entries

5 entries across 5 versions & 2 rubygems

Version Path
codenamev_bitbucket_api-0.4.1 lib/bitbucket_rest_api/request/jsonize.rb
codenamev_bitbucket_api-0.4.0 lib/bitbucket_rest_api/request/jsonize.rb
reenhanced_bitbucket_api-0.3.2 lib/bitbucket_rest_api/request/jsonize.rb
reenhanced_bitbucket_api-0.3.1 lib/bitbucket_rest_api/request/jsonize.rb
reenhanced_bitbucket_api-0.3.0 lib/bitbucket_rest_api/request/jsonize.rb