Sha256: 52b5e2d4e58605e248a13eb9c7f8c74816c974d492e3376657917337a7835d93

Contents?: true

Size: 1.3 KB

Versions: 11

Compression:

Stored size: 1.3 KB

Contents

# From https://github.com/lostisland/faraday_middleware/blob/master/lib/faraday_middleware/request/encode_json.rb
require 'faraday'
require 'json'

module Terminal
  module RequestExt
    class EncodeJson < Faraday::Middleware
      CONTENT_TYPE = 'Content-Type'.freeze
      MIME_TYPE    = 'application/json'.freeze

      dependency do
        require 'json' unless defined?(::JSON)
      end

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

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

      def match_content_type(env)
        if process_request?(env)
          env[:request_headers][CONTENT_TYPE] ||= MIME_TYPE
          yield env[:body] unless env[:body].respond_to?(:to_str)
        end
      end

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

      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

  end
end

Faraday::Request.register_middleware :encode_json => Terminal::RequestExt::EncodeJson

Version data entries

11 entries across 11 versions & 1 rubygems

Version Path
cc-terminal-0.1.4 lib/terminal/request/encode_json.rb
cc-terminal-0.1.2 lib/terminal/request/encode_json.rb
cc-terminal-0.1.1 lib/terminal/request/encode_json.rb
cc-terminal-0.1.0 lib/terminal/request/encode_json.rb
cc-terminal-0.0.8 lib/terminal/request/encode_json.rb
cc-terminal-0.0.7 lib/terminal/request/encode_json.rb
cc-terminal-0.0.6 lib/terminal/request/encode_json.rb
cc-terminal-0.0.5 lib/terminal/request/encode_json.rb
cc-terminal-0.0.4 lib/terminal/request/encode_json.rb
cc-terminal-0.0.3 lib/terminal/request/encode_json.rb
cc-terminal-0.0.2 lib/terminal/request/encode_json.rb