Class: GraphQL::ActiveRecordExtensions::Field

Inherits:
Field
  • Object
show all
Defined in:
lib/graphql/active_record_extensions/field.rb

Instance Method Summary collapse

Constructor Details

#initialize(model:, type:) ⇒ Field

Returns a new instance of Field.



8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
# File 'lib/graphql/active_record_extensions/field.rb', line 8

def initialize(model:, type:)
  @model = model

  self.type = type
  self.description = "Find a #{model.name} by ID"
  self.arguments = {
    'id' => GraphQL::Argument.define do
      type !GraphQL::ID_TYPE
      description "Id for record"
    end,
    'use_uuid' => GraphQL::Argument.define do
      type GraphQL::BOOLEAN_TYPE
      description "Whether or not to use UUID"
    end,
  }
end

Instance Method Details

#resolve(object, arguments, ctx) ⇒ Object

override of GraphQL::Field.resolve basically just provides the final object (in this case an AR model) can check RDoc for graphql-ruby gem

Parameters:

  • object

    not used

  • arguments

    List List of Arguments for the field (i.e. id, uuid, etc.)

  • ctx (GraphQL::Context)

    the context of the GraphQL query

Returns:

  • eager-loaded ActiveRecord model



35
36
37
38
39
40
41
42
43
44
45
46
47
48
# File 'lib/graphql/active_record_extensions/field.rb', line 35

def resolve(object, arguments, ctx)
  includes = map_includes(@model, ctx.ast_node.selections, ctx)

  model_with_includes = include_in_model(@model, includes)

  if arguments['use_uuid']
    model_with_includes.find_by_uuid(arguments['id'])
  else
    model_with_includes.find(arguments['id'])
  end

  rescue ActiveRecord::ConfigurationError => e
    @model.find(arguments['id'])
end