Sha256: 795bb241171b49555ebfc7e65dc4dd2da87496af0a3b4916a29c2023bd9d860f

Contents?: true

Size: 898 Bytes

Versions: 1

Compression:

Stored size: 898 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 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

1 entries across 1 versions & 1 rubygems

Version Path
httpx-0.17.0 lib/httpx/transcoder/json.rb