Class: GraphqlDevise::ResourceLoader

Inherits:
Object
  • Object
show all
Defined in:
lib/graphql_devise/resource_loader.rb

Instance Method Summary collapse

Constructor Details

#initialize(resource, options = {}, routing = false) ⇒ ResourceLoader

Returns a new instance of ResourceLoader.



5
6
7
8
9
10
# File 'lib/graphql_devise/resource_loader.rb', line 5

def initialize(resource, options = {}, routing = false)
  @resource           = resource
  @options            = options
  @routing            = routing
  @default_operations = DefaultOperations::MUTATIONS.merge(DefaultOperations::QUERIES)
end

Instance Method Details

#call(query, mutation) ⇒ Object



12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
# File 'lib/graphql_devise/resource_loader.rb', line 12

def call(query, mutation)
  # clean_options responds to all keys defined in GraphqlDevise::MountMethod::SUPPORTED_OPTIONS
  clean_options = MountMethod::OptionSanitizer.new(@options).call!

  unless @resource.is_a?(Class)
    raise(
      InvalidMountOptionsError,
      'A class must be provided when mounting a model. String values are no longer supported.'
    )
  end

  # Necesary when mounting a resource via route file as Devise forces the reloading of routes
  return clean_options if ::GraphqlDevise.resource_mounted?(@resource) && @routing

  validate_options!(clean_options)

  authenticatable_type = clean_options.authenticatable_type.presence ||
                         "Types::#{@resource}Type".safe_constantize ||
                         Types::AuthenticatableType

  prepared_mutations = prepare_mutations(@resource, clean_options, authenticatable_type)

  if prepared_mutations.any? && mutation.blank?
    raise ::GraphqlDevise::Error, 'You need to provide a mutation type unless all mutations are skipped'
  end

  begin
    prepared_mutations.each do |action, prepared_mutation|
      mutation.field(action, mutation: prepared_mutation, authenticate: false)
    end
  rescue ArgumentError
    raise unless Gem::Version.new(GraphQL::VERSION) >= Gem::Version.new('2.0')

    raise_undefined_field_class_error('MutationType')
  end

  prepared_resolvers = prepare_resolvers(@resource, clean_options, authenticatable_type)

  if prepared_resolvers.any? && query.blank?
    raise ::GraphqlDevise::Error, 'You need to provide a query type unless all queries are skipped'
  end

  begin
    prepared_resolvers.each do |action, resolver|
      query.field(action, resolver: resolver, authenticate: false)
    end
  rescue ArgumentError
    raise unless Gem::Version.new(GraphQL::VERSION) >= Gem::Version.new('2.0')

    raise_undefined_field_class_error('QueryType')
  end

  ::GraphqlDevise.add_mapping(::GraphqlDevise.to_mapping_name(@resource).to_sym, @resource)
  ::GraphqlDevise.mount_resource(@resource) if @routing

  clean_options
end