Sha256: 99fc8190c16140b52e8042d50cc5a79fb217b2b6d161585581eceafc763967cf

Contents?: true

Size: 1.24 KB

Versions: 6

Compression:

Stored size: 1.24 KB

Contents

# frozen_string_literal: true

# Released under the MIT License.
# Copyright, 2018-2024, by Samuel Williams.

require "json"

require "protocol/http/body/wrapper"
require "protocol/http/body/buffered"

require_relative "generic"

module Async
	module REST
		module Wrapper
			class JSON < Generic
				APPLICATION_JSON = "application/json".freeze
				APPLICATION_JSON_STREAM = "application/json; boundary=NL".freeze
				
				def initialize(content_type = APPLICATION_JSON)
					@content_type = content_type
				end
				
				attr :content_type
				
				def split(*arguments)
					@content_type.split
				end
				
				def prepare_request(request, payload)
					request.headers["accept"] ||= @content_type
					
					if payload
						request.headers["content-type"] = @content_type
						
						request.body = ::Protocol::HTTP::Body::Buffered.new([
							::JSON.dump(payload)
						])
					end
				end
				
				class Parser < ::Protocol::HTTP::Body::Wrapper
					def join
						::JSON.parse(super, symbolize_names: true)
					end
				end
				
				def parser_for(response)
					if content_type = response.headers["content-type"]
						if content_type.start_with? @content_type
							return Parser
						end
					end
					
					return super
				end
			end
		end
	end
end

Version data entries

6 entries across 6 versions & 1 rubygems

Version Path
async-rest-0.19.1 lib/async/rest/wrapper/json.rb
async-rest-0.19.0 lib/async/rest/wrapper/json.rb
async-rest-0.18.0 lib/async/rest/wrapper/json.rb
async-rest-0.17.0 lib/async/rest/wrapper/json.rb
async-rest-0.16.0 lib/async/rest/wrapper/json.rb
async-rest-0.15.0 lib/async/rest/wrapper/json.rb