Sha256: 64eb4bc87984a549359402d844463b4cee70a05e6193315c7a111ce2606dd2be

Contents?: true

Size: 1.82 KB

Versions: 1

Compression:

Stored size: 1.82 KB

Contents

# frozen_string_literal: true

require 'faraday'

module Faraday
  module HalJson
    # 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 Request < Faraday::Middleware
      CONTENT_TYPE = 'Content-Type'
      MIME_TYPE    = 'application/hal+json'

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

      private

      def encode(data)
        if options[:encoder].is_a?(Array) && options[:encoder].size >= 2
          options[:encoder][0].public_send(options[:encoder][1], data)
        elsif options[:encoder].respond_to?(:dump)
          options[:encoder].dump(data)
        else
          ::JSON.generate(data)
        end
      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 == MIME_TYPE)
      end

      def body?(env)
        body = env[:body]
        case body
        when true, false
          true
        when nil
          # NOTE: nil can be converted to `"null"`, but this middleware doesn't process `nil` for the compatibility.
          false
        else
          !(body.respond_to?(:to_str) && body.empty?)
        end
      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

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
faraday_hal_middleware-0.2.0 lib/faraday/hal_json/request.rb