Sha256: 293e9c75c8e542a9c0d1a1c32d4a10f9288136d6a3133af07d448db352373e9c

Contents?: true

Size: 1.71 KB

Versions: 5

Compression:

Stored size: 1.71 KB

Contents

# frozen_string_literal: true

module GraphqlRails
  # executes GraphQL queries and returns json
  class QueryRunner
    require 'graphql_rails/router'
    require 'graphql_rails/concerns/service'

    include ::GraphqlRails::Service

    def initialize(params:, context: {}, schema: nil, router: nil, group: nil, **schema_options) # rubocop:disable Metrics/ParameterLists
      @group = group
      @graphql_schema = schema
      @params = params
      @router = router
      @initial_context = context
      @schema_options = schema_options
    end

    def call
      graphql_schema.execute(
        params[:query],
        variables: variables,
        operation_name: params[:operationName],
        context: context,
        **schema_options
      )
    end

    private

    attr_reader :schema_options, :params, :group, :initial_context

    def context
      initial_context.merge(graphql_group: group)
    end

    def variables
      ensure_hash(params[:variables])
    end

    def graphql_schema
      @graphql_schema ||= router_schema
    end

    def router
      @router ||= ::GraphqlRouter
    end

    def router_schema
      router.graphql_schema(group)
    end

    def ensure_hash(ambiguous_param)
      if ambiguous_param.blank?
        {}
      elsif ambiguous_param.is_a?(String)
        ensure_hash(JSON.parse(ambiguous_param))
      elsif kind_of_hash?(ambiguous_param)
        ambiguous_param
      else
        raise ArgumentError, "Unexpected parameter: #{ambiguous_param.inspect}"
      end
    end

    def kind_of_hash?(object)
      return true if object.is_a?(Hash)

      defined?(ActionController) &&
        defined?(ActionController::Parameters) &&
        object.is_a?(ActionController::Parameters)
    end
  end
end

Version data entries

5 entries across 5 versions & 1 rubygems

Version Path
graphql_rails-3.0.0 lib/graphql_rails/query_runner.rb
graphql_rails-2.4.0 lib/graphql_rails/query_runner.rb
graphql_rails-2.3.0 lib/graphql_rails/query_runner.rb
graphql_rails-2.2.0 lib/graphql_rails/query_runner.rb
graphql_rails-2.1.0 lib/graphql_rails/query_runner.rb