Sha256: add27c340d458a5ce3916131c949ca0e24c89d4ce3f205ff9d7a5e3bec2baef5

Contents?: true

Size: 1.42 KB

Versions: 33

Compression:

Stored size: 1.42 KB

Contents

# frozen_string_literal: true

require 'json'

module Faraday
  class Request
    # 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.
    class Json < Middleware
      MIME_TYPE = 'application/json'
      MIME_TYPE_REGEX = %r{^application/(vnd\..+\+)?json$}.freeze

      def on_request(env)
        match_content_type(env) do |data|
          env[:body] = encode(data)
        end
      end

      private

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

      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

      def process_request?(env)
        type = request_type(env)
        body?(env) && (type.empty? || type.match?(MIME_TYPE_REGEX))
      end

      def body?(env)
        (body = env[:body]) && !(body.respond_to?(:to_str) && 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(json: Faraday::Request::Json)

Version data entries

33 entries across 33 versions & 7 rubygems

Version Path
faraday-1.10.4 lib/faraday/request/json.rb
avalara_sdk-24.2.29 vendor/bundle/ruby/2.7.0/gems/faraday-1.10.3/lib/faraday/request/json.rb
fluent-plugin-google-cloud-logging-on-prem-0.1.0 vendor/ruby/3.1.0/gems/faraday-2.7.4/lib/faraday/request/json.rb
zilla-0.2.0 vendor/bundle/ruby/3.2.0/gems/faraday-2.7.4/lib/faraday/request/json.rb
faraday-2.7.4 lib/faraday/request/json.rb
faraday-1.10.3 lib/faraday/request/json.rb
faraday-2.7.3 lib/faraday/request/json.rb
faraday-2.7.2 lib/faraday/request/json.rb
tdiary-5.2.4 vendor/bundle/ruby/3.1.0/gems/faraday-2.5.2/lib/faraday/request/json.rb
faraday-2.7.1 lib/faraday/request/json.rb
faraday-2.7.0 lib/faraday/request/json.rb
faraday-2.6.0 lib/faraday/request/json.rb
tdiary-5.2.3 vendor/bundle/ruby/3.1.0/gems/faraday-2.5.2/lib/faraday/request/json.rb
faraday-1.10.2 lib/faraday/request/json.rb
faraday-2.5.2 lib/faraday/request/json.rb
faraday-2.5.1 lib/faraday/request/json.rb
faraday-2.5.0 lib/faraday/request/json.rb
faraday-1.10.1 lib/faraday/request/json.rb
faraday-2.4.0 lib/faraday/request/json.rb
tdiary-5.2.2 vendor/bundle/ruby/3.1.0/gems/faraday-2.3.0/lib/faraday/request/json.rb