Sha256: de7d51ea3b6bc311702b7c348f311ae4386f21279539537ccff153051eb70a5b

Contents?: true

Size: 905 Bytes

Versions: 23

Compression:

Stored size: 905 Bytes

Contents

# frozen_string_literal: true

require "forwardable"
require "json"

module HTTPX::Transcoder
  module JSON
    JSON_REGEX = %r{\bapplication/(?:vnd\.api\+)?json\b}i.freeze

    using HTTPX::RegexpExtensions unless Regexp.method_defined?(:match?)

    module_function

    class Encoder
      extend Forwardable

      def_delegator :@raw, :to_s

      def_delegator :@raw, :bytesize

      def initialize(json)
        @raw = ::JSON.dump(json)
        @charset = @raw.encoding.name.downcase
      end

      def content_type
        "application/json; charset=#{@charset}"
      end
    end

    def encode(json)
      Encoder.new(json)
    end

    def decode(response)
      content_type = response.content_type.mime_type

      raise HTTPX::Error, "invalid json mime type (#{content_type})" unless JSON_REGEX.match?(content_type)

      ::JSON.method(:parse)
    end
  end
  register "json", JSON
end

Version data entries

23 entries across 23 versions & 1 rubygems

Version Path
httpx-0.18.2 lib/httpx/transcoder/json.rb
httpx-0.18.1 lib/httpx/transcoder/json.rb
httpx-0.18.0 lib/httpx/transcoder/json.rb