Sha256: a8be4fc122c133699204519fd18cf8b0d4db1c716e9b7a621653c5b81c0a0770

Contents?: true

Size: 1.57 KB

Versions: 4

Compression:

Stored size: 1.57 KB

Contents

# frozen_string_literal: true

require 'json'
require 'net/http'

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

module Artemis
  module Adapters
    class NetHttpAdapter < AbstractAdapter
      # Makes an HTTP request for GraphQL query.
      def execute(document:, operation_name: nil, variables: {}, context: {})
        request = Net::HTTP::Post.new(uri.request_uri)

        request.basic_auth(uri.user, uri.password) if uri.user || uri.password

        DEFAULT_HEADERS.merge(headers(context)).each { |name, value| request[name] = value }

        body = {}
        body["query"] = document.to_query_string
        body["variables"] = variables if variables.any?
        body["operationName"] = operation_name if operation_name
        request.body = JSON.generate(body)

        response = connection.request(request)

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

      # Returns a fresh Net::HTTP object that creates a new connection.
      def connection
        Net::HTTP.new(uri.host, uri.port).tap do |client|
          client.use_ssl       = uri.scheme == "https"
          client.open_timeout  = timeout
          client.read_timeout  = timeout
          client.write_timeout = timeout if client.respond_to?(:write_timeout=)
        end
      end
    end
  end
end

Version data entries

4 entries across 4 versions & 1 rubygems

Version Path
artemis-0.6.0 lib/artemis/adapters/net_http_adapter.rb
artemis-0.5.2 lib/artemis/adapters/net_http_adapter.rb
artemis-0.5.1 lib/artemis/adapters/net_http_adapter.rb
artemis-0.5.0 lib/artemis/adapters/net_http_adapter.rb