Sha256: bffa5b687085a39eb59b075209506cc0244098665e03fdbe0d431dd39db2b1bf

Contents?: true

Size: 1.33 KB

Versions: 4

Compression:

Stored size: 1.33 KB

Contents

# frozen_string_literal: true

module Ibrain
  class GraphqlController < Ibrain::BaseController
    def execute
      query, variables, operation_name = normalize_entity

      result = schema.execute(
        query,
        variables: variables,
        context: {
          session: session,
          current_user: try_ibrain_current_user
        },
        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
  end
end

Version data entries

4 entries across 4 versions & 1 rubygems

Version Path
ibrain-core-0.1.7 app/controllers/ibrain/graphql_controller.rb
ibrain-core-0.1.6 app/controllers/ibrain/graphql_controller.rb
ibrain-core-0.1.5 app/controllers/ibrain/graphql_controller.rb
ibrain-core-0.1.4 app/controllers/ibrain/graphql_controller.rb