Sha256: fc0c716b7e82662c2e226f96ef12bc39fcd091d5cda2ac4a0ab516fab72d64ca

Contents?: true

Size: 1.8 KB

Versions: 6

Compression:

Stored size: 1.8 KB

Contents

# frozen_string_literal: true

require 'delegate'
require 'json'

require 'curb'

require 'artemis/adapters/abstract_adapter'
require 'artemis/exceptions'

module Artemis
  module Adapters
    class CurbAdapter < AbstractAdapter
      attr_reader :multi

      def initialize(uri, service_name: , timeout: , pool_size: , adapter_options: {})
        super

        @multi = Curl::Multi.new
        @multi.pipeline = Curl::CURLPIPE_MULTIPLEX if defined?(Curl::CURLPIPE_MULTIPLEX)
      end

      def multiplex(queries, context: {})
        make_request({ _json: queries }, context)
      end

      def execute(document:, operation_name: nil, variables: {}, context: {})
        body = {}
        body["query"] = document.to_query_string
        body["variables"] = variables if variables.any?
        body["operationName"] = operation_name if operation_name

        make_request(body, context)
      end

      private

      def make_request(body, context)
        easy = Curl::Easy.new(uri.to_s)

        easy.timeout   = timeout
        easy.multi     = multi
        easy.headers   = DEFAULT_HEADERS.merge(headers(context))
        easy.post_body = JSON.generate(body)

        if defined?(Curl::CURLPIPE_MULTIPLEX)
          # This ensures libcurl waits for the connection to reveal if it is
          # possible to pipeline/multiplex on before it continues.
          easy.setopt(Curl::CURLOPT_PIPEWAIT, 1)
          easy.version = Curl::HTTP_2_0
        end

        easy.http_post

        case easy.response_code
        when 200, 400
          JSON.parse(easy.body)
        when 500..599
          raise Artemis::GraphQLServerError, "Received server error status #{easy.response_code}: #{easy.body}"
        else
          { "errors" => [{ "message" => "#{easy.response_code} #{easy.body}" }] }
        end
      end
    end
  end
end

Version data entries

6 entries across 6 versions & 1 rubygems

Version Path
artemis-1.1.0 lib/artemis/adapters/curb_adapter.rb
artemis-1.0.2 lib/artemis/adapters/curb_adapter.rb
artemis-1.0.0 lib/artemis/adapters/curb_adapter.rb
artemis-0.9.0 lib/artemis/adapters/curb_adapter.rb
artemis-0.8.0 lib/artemis/adapters/curb_adapter.rb
artemis-0.7.0 lib/artemis/adapters/curb_adapter.rb