Class: GraphQL::ActiveRecordExtensions::Field

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

Class Method Summary collapse

Class Method Details

.generate(model:, resolve_type:, name: nil) ⇒ Object



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

def self.generate(model:, resolve_type:, name: nil)
  n = name || model.name.underscore
  GraphQL::Field.define do
    name(n)
    type(resolve_type)
    description("Find a #{model.name} by ID/UUID")

    argument :id, !GraphQL::ID_TYPE
    argument :use_uuid, GraphQL::BOOLEAN_TYPE

    resolve -> (object, arguments, context) do
      GraphQL::ActiveRecordExtensions::Field.resolve_it(model, object, arguments, context)
    end
  end
end

.resolve_it(model, 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



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

def self.resolve_it(model, 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