Sha256: 524d3d57f13e3cdfd030cadf2a393416cab6f3bc27d4760e5b599d575d95f72a

Contents?: true

Size: 1.91 KB

Versions: 6

Compression:

Stored size: 1.91 KB

Contents

# frozen_string_literal: true

module Ibrain
  module Core
    class GraphqlController < ::Ibrain::BaseController
      include Devise::Controllers::ScopedViews

      before_action :map_user_class_to_request

      helpers = %w(resource scope_name resource_name signed_in_resource
                   resource_class resource_params devise_mapping)
      helper_method(*helpers)

      def execute
        query, variables, operation_name = normalize_entity

        result = schema.execute(
          query,
          variables: variables,
          context: {
            session: session,
            current_user: try_ibrain_current_user,
            controller: self,
            request: request
          },
          operation_name: operation_name
        )

        render_json_ok(result['data'], nil, result['errors'])
      end

      protected

      def normalize_entity
        query = params[:query]
        operation_name = params[:operationName]
        variables = prepare_variables(params[:variables])

        [query, variables, operation_name]
      end

      # Handle variables in form data, JSON body, or a blank value
      def prepare_variables(variables_param)
        case variables_param
        when String
          if variables_param.present?
            JSON.parse(variables_param) || {}
          else
            {}
          end
        when Hash
          variables_param
        when ActionController::Parameters
          variables_param.to_unsafe_hash # GraphQLRuby will validate name and type of incoming variables.
        when nil
          {}
        else
          raise ArgumentError, "Unexpected parameter: #{variables_param}"
        end
      end

      def schema
        Ibrain::Config.graphql_schema.safe_constantize
      end

      def map_user_class_to_request
        return if request.env['devise.mapping'].present?

        request.env['devise.mapping'] = Ibrain.user_class
      end
    end
  end
end

Version data entries

6 entries across 6 versions & 1 rubygems

Version Path
ibrain-core-0.2.7 app/controllers/ibrain/core/graphql_controller.rb
ibrain-core-0.2.6 app/controllers/ibrain/core/graphql_controller.rb
ibrain-core-0.2.5 app/controllers/ibrain/core/graphql_controller.rb
ibrain-core-0.2.4 app/controllers/ibrain/core/graphql_controller.rb
ibrain-core-0.2.3 app/controllers/ibrain/core/graphql_controller.rb
ibrain-core-0.2.2 app/controllers/ibrain/core/graphql_controller.rb