Class: GraphQL::Rails::Operations::QueryDefinition

Inherits:
DSL
  • Object
show all
Defined in:
lib/graphql/rails/operations.rb

Overview

DSL for query definition. TODO: Support resolve-only blocks.

Direct Known Subclasses

MutationDefinition

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods inherited from DSL

#run

Constructor Details

#initialize(klass) ⇒ QueryDefinition

Returns a new instance of QueryDefinition.



88
89
90
91
# File 'lib/graphql/rails/operations.rb', line 88

def initialize(klass)
  @klass = klass
  @field = ::GraphQL::Field.new
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method in the class GraphQL::Rails::DSL

Instance Attribute Details

#fieldObject (readonly)

Returns the value of attribute field.



86
87
88
# File 'lib/graphql/rails/operations.rb', line 86

def field
  @field
end

Instance Method Details

#argument(name, type, required = false) ⇒ Object



111
112
113
114
115
116
117
# File 'lib/graphql/rails/operations.rb', line 111

def argument(name, type, required = false)
  argument = ::GraphQL::Argument.define do
    name Types.to_field_name(name)
    type Types.resolve(type, required == :required)
  end
  @field.arguments[argument.name] = argument
end

#description(description) ⇒ Object



107
108
109
# File 'lib/graphql/rails/operations.rb', line 107

def description(description)
  @field.description = description
end

#name(name) ⇒ Object



93
94
95
96
# File 'lib/graphql/rails/operations.rb', line 93

def name(name)
  @name = name
  @field.name = Types.to_field_name(name)
end

#resolve(&block) ⇒ Object



119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
# File 'lib/graphql/rails/operations.rb', line 119

def resolve(&block)
  @field.resolve = -> (obj, args, ctx) do
    # Instantiate the Operations class with state on this query.
    instance = @klass.new({
      op: :query, name: @name, type: @type,
      obj: obj, args: Fields.new(args), ctx: ctx, context: ctx
    })

    begin
      # Run callbacks for this Operations class.
      instance.run_callbacks(:perform_operation) do
        # Call out to the app-defined resolver.
        instance.instance_eval(&block)
      end
    rescue => e
      # Surface messages from standard errors in GraphQL response.
      ::GraphQL::ExecutionError.new(e.message)
    rescue ::Exception => e
      # Log and genericize other runtime errors.
      Rails.logger.error "Unexpected exception during query: #{@name}"
      Rails.logger.exception e
      ::GraphQL::ExecutionError.new('Internal error')
    end
  end
end

#type(type) ⇒ Object



102
103
104
105
# File 'lib/graphql/rails/operations.rb', line 102

def type(type)
  @type = type
  @field.type = Types.resolve(type)
end

#uses(type) ⇒ Object



98
99
100
# File 'lib/graphql/rails/operations.rb', line 98

def uses(type)
  Types.explicit.push Types.resolve(type)
end