lighthouse-graphql 0.7.1 → 0.7.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (42) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +58 -1
  3. data/docs/directives.md +7 -4
  4. data/docs/filtering-and-ordering.md +52 -0
  5. data/docs/getting-started.md +44 -11
  6. data/lib/lighthouse/ast_builder.rb +16 -4
  7. data/lib/lighthouse/cache_control.rb +14 -2
  8. data/lib/lighthouse/complexity.rb +11 -1
  9. data/lib/lighthouse/directive_resolvers/aggregate_resolver.rb +17 -1
  10. data/lib/lighthouse/directive_resolvers/all_resolver.rb +13 -1
  11. data/lib/lighthouse/directive_resolvers/association_resolvers.rb +70 -16
  12. data/lib/lighthouse/directive_resolvers/auth_resolver.rb +10 -1
  13. data/lib/lighthouse/directive_resolvers/base.rb +44 -22
  14. data/lib/lighthouse/directive_resolvers/broadcast_resolver.rb +12 -1
  15. data/lib/lighthouse/directive_resolvers/cache_resolvers.rb +28 -3
  16. data/lib/lighthouse/directive_resolvers/can_resolvers.rb +62 -9
  17. data/lib/lighthouse/directive_resolvers/count_resolver.rb +16 -1
  18. data/lib/lighthouse/directive_resolvers/event_resolver.rb +13 -1
  19. data/lib/lighthouse/directive_resolvers/field_resolver.rb +6 -1
  20. data/lib/lighthouse/directive_resolvers/find_resolver.rb +13 -1
  21. data/lib/lighthouse/directive_resolvers/first_resolver.rb +13 -1
  22. data/lib/lighthouse/directive_resolvers/guard_resolver.rb +10 -1
  23. data/lib/lighthouse/directive_resolvers/method_resolver.rb +13 -1
  24. data/lib/lighthouse/directive_resolvers/model_mutation_resolver.rb +75 -16
  25. data/lib/lighthouse/directive_resolvers/paginate_resolver.rb +17 -2
  26. data/lib/lighthouse/directive_resolvers/rename_resolver.rb +14 -1
  27. data/lib/lighthouse/directive_resolvers/subscription_resolver.rb +13 -1
  28. data/lib/lighthouse/directive_resolvers/validator_resolver.rb +13 -1
  29. data/lib/lighthouse/directives/arguments/base.rb +18 -0
  30. data/lib/lighthouse/directives/arguments/filters.rb +16 -7
  31. data/lib/lighthouse/directives/definitions.rb +43 -6
  32. data/lib/lighthouse/document_ast.rb +12 -0
  33. data/lib/lighthouse/enum_directive.rb +6 -1
  34. data/lib/lighthouse/feature_directive.rb +13 -1
  35. data/lib/lighthouse/graphql/version.rb +1 -1
  36. data/lib/lighthouse/graphql_ruby_patches.rb +26 -2
  37. data/lib/lighthouse/ide_helper.rb +7 -6
  38. data/lib/lighthouse/scalar_coercion.rb +4 -1
  39. data/lib/lighthouse/tasks/lighthouse.rake +8 -0
  40. data/lib/lighthouse/type_resolution.rb +8 -2
  41. data/sig/lighthouse/graphql.rbs +4 -0
  42. metadata +1 -1
@@ -1,6 +1,24 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  class Lighthouse::GraphQL::DirectiveResolvers::BaseDirectiveResolver
4
+ # A directive argument's SDL with its description, indented to sit in a
5
+ # definition's parentheses (see the constants below, and `definition`s).
6
+ def self.argument_sdl(declaration, description)
7
+ %( "#{description.gsub(/["\\]/) { |c| "\\#{c}" }}"\n #{declaration})
8
+ end
9
+
10
+ # The arguments many directives share, to splice into a definition with
11
+ # `#{MODEL_ARGUMENT}`.
12
+ MODEL_ARGUMENT = argument_sdl(
13
+ 'model: String',
14
+ "The class name of the model to use. Defaults to the model of another directive on the field, else the field's return type."
15
+ )
16
+ SCOPES_ARGUMENT = argument_sdl('scopes: [String!]', 'Names of model scopes to apply to the underlying query, in order.')
17
+ RELATION_ARGUMENT = argument_sdl(
18
+ 'relation: String',
19
+ "The name of the association on the parent model. Defaults to the field's name in snake_case."
20
+ )
21
+
4
22
  def initialize(field_def, type_def, directive_node, opts = {})
5
23
  @field_def = field_def
6
24
  @type_def = type_def
@@ -29,13 +47,13 @@ class Lighthouse::GraphQL::DirectiveResolvers::BaseDirectiveResolver
29
47
  # Compose argument-builder directives (@eq, @neq, @in, @notIn, @like,
30
48
  # @where, @orderBy, @whereConditions, @whereHasConditions) onto the relation, in SDL argument order, for each
31
49
  # field argument that carries one and that the client supplied a value
32
- # for — and for the input fields of an argument carrying @nest.
50
+ # for — and for the fields of the input objects the client sent, at any depth.
33
51
  def apply_arg_builders(relation, args_h, ctx = nil)
34
52
  return relation unless relation.respond_to?(:where)
35
53
  return relation unless @field_def.ast_node
36
54
 
37
- arg_builders.each do |path, arg_node, dnode, builder_class|
38
- relation = apply_arg_builder(relation, args_h, ctx, [path, arg_node, dnode, builder_class])
55
+ arg_builders(args_h).each do |values, node, dnode, builder_class|
56
+ relation = apply_arg_builder(relation, values, ctx, [[node.name], node, dnode, builder_class])
39
57
  end
40
58
 
41
59
  relation
@@ -123,35 +141,39 @@ class Lighthouse::GraphQL::DirectiveResolvers::BaseDirectiveResolver
123
141
  hash.is_a?(Hash) && Lighthouse::Support::Naming.candidate_keys(path.last).any? { |key| hash.key?(key) }
124
142
  end
125
143
 
126
- # [path, node, directive, builder class] for every argument-builder
127
- # directive, in SDL order. An argument carrying @nest adds its input type's
128
- # fields', at any depth, with their path into the value.
129
- def arg_builders
130
- (@field_def.ast_node.arguments || []).flat_map do |arg_node|
131
- builders_of(arg_node, [arg_node.name], @field_def.arguments[arg_node.name])
132
- end
144
+ # Did the client send an argument or input field, at any depth, that
145
+ # carries an argument-builder directive? As PHP Lighthouse's wouldEnhanceBuilder.
146
+ def filtering?(args_h)
147
+ arg_builders(args_h).any? { |values, node, _dnode, _builder_class| arg_present?(values, [node.name]) }
148
+ end
149
+
150
+ # [values, node, directive, builder class] for every argument-builder
151
+ # directive on the field's arguments, in SDL order, then on the fields of the
152
+ # input objects the client sent for them (each of a list), at any depth,
153
+ # as PHP Lighthouse's applyArgBuilderDirectives goes through them. `values`
154
+ # holds the node's value: the arguments, or the input object it is a field of.
155
+ def arg_builders(args_h)
156
+ builders_in(@field_def.ast_node.arguments || [], @field_def.arguments, args_h)
133
157
  end
134
158
 
135
- def builders_of(node, path, argument)
159
+ def builders_in(nodes, arguments, values)
136
160
  registry = Lighthouse::DirectiveRegistry.default
137
- own = (node.directives || []).filter_map do |dnode|
138
- builder_class = dnode.name == 'builder' ? :builder : registry.arg_builder_class(dnode.name)
139
- [path, node, dnode, builder_class] if builder_class
161
+ nodes.flat_map do |node|
162
+ own = (node.directives || []).filter_map do |dnode|
163
+ builder_class = dnode.name == 'builder' ? :builder : registry.arg_builder_class(dnode.name)
164
+ [values, node, dnode, builder_class] if builder_class
165
+ end
166
+ own + nested_builders(arguments[node.name], dig_arg(values, [node.name]))
140
167
  end
141
- own + (argument && nest?(node) ? nested_builders(argument, path) : [])
142
168
  end
143
169
 
144
- def nest?(node)
145
- (node.directives || []).any? { |d| d.name == 'nest' }
146
- end
170
+ def nested_builders(argument, value)
171
+ return [] if argument.nil? || value.nil?
147
172
 
148
- def nested_builders(argument, path)
149
173
  type = argument.type.unwrap
150
174
  return [] unless type.kind.input_object?
151
175
 
152
- type.arguments.each_value.flat_map do |field|
153
- field.ast_node ? builders_of(field.ast_node, path + [field.ast_node.name], field) : []
154
- end
176
+ [value].flatten.compact.flat_map { |input| builders_in(type.arguments.values.filter_map(&:ast_node), type.arguments, input) }
155
177
  end
156
178
 
157
179
  # The client's value at `path` (an argument, then input fields), or nil.
@@ -12,7 +12,18 @@ class Lighthouse::GraphQL::DirectiveResolvers::BroadcastDirectiveResolver < Ligh
12
12
  def self.directive_name = 'broadcast'
13
13
 
14
14
  def self.definition
15
- 'directive @broadcast(subscription: String!, shouldQueue: Boolean) repeatable on FIELD_DEFINITION'
15
+ <<~GRAPHQL.chomp
16
+ """
17
+ Broadcast the result of the field to the subscribers of a subscription, once it resolved successfully.
18
+ A null result, or an error, broadcasts nothing.
19
+ """
20
+ directive @broadcast(
21
+ "The name of the subscription field to trigger."
22
+ subscription: String!
23
+ "Broadcast in a background job instead of in the request. Defaults to Config.queue_broadcasts."
24
+ shouldQueue: Boolean
25
+ ) repeatable on FIELD_DEFINITION
26
+ GRAPHQL
16
27
  end
17
28
 
18
29
  def define_resolver(target_type_class)
@@ -14,7 +14,21 @@ module Lighthouse::GraphQL::DirectiveResolvers
14
14
  # is reported through Config.on_error and returned uncached.
15
15
  class CacheDirectiveResolver < Lighthouse::GraphQL::DirectiveResolvers::BaseDirectiveResolver
16
16
  def self.directive_name = 'cache'
17
- def self.definition = 'directive @cache(maxAge: Int, private: Boolean = false) on FIELD_DEFINITION'
17
+
18
+ def self.definition
19
+ <<~GRAPHQL.chomp
20
+ """
21
+ Cache the field's resolved value in Rails.cache.
22
+ The key covers the parent object, the field and its arguments.
23
+ """
24
+ directive @cache(
25
+ "How long, in seconds, the value is kept. Without it, until @clearCache or eviction."
26
+ maxAge: Int
27
+ "Keep a value per authenticated user, instead of one shared by all (guests share one)."
28
+ private: Boolean = false
29
+ ) on FIELD_DEFINITION
30
+ GRAPHQL
31
+ end
18
32
 
19
33
  ROOT_TYPES = %w[Query Mutation Subscription].freeze
20
34
 
@@ -88,8 +102,19 @@ module Lighthouse::GraphQL::DirectiveResolvers
88
102
  def self.directive_name = 'clearCache'
89
103
 
90
104
  def self.definition
91
- 'directive @clearCache(type: String!, idSource: ClearCacheIdSource, field: String) ' \
92
- 'repeatable on FIELD_DEFINITION'
105
+ <<~GRAPHQL.chomp
106
+ """
107
+ On a mutation, invalidate @cache entries once the field resolved successfully.
108
+ """
109
+ directive @clearCache(
110
+ "The name of the type whose entries to clear. Alone, it clears all of that type's entries."
111
+ type: String!
112
+ "Narrow the entries to those of the objects with the ids found at this path."
113
+ idSource: ClearCacheIdSource
114
+ "Narrow the entries to those of this field."
115
+ field: String
116
+ ) repeatable on FIELD_DEFINITION
117
+ GRAPHQL
93
118
  end
94
119
 
95
120
  def self.type_definitions
@@ -19,8 +19,16 @@ module Lighthouse::GraphQL::DirectiveResolvers
19
19
  # generic "This action is unauthorized.", or return `returnValue` instead.
20
20
  # All are repeatable; they run after @guard and before validation.
21
21
  class CanDirectiveResolver < Lighthouse::GraphQL::DirectiveResolvers::BaseDirectiveResolver
22
- COMMON_ARGUMENTS = 'ability: String!, injectArgs: Boolean = false, args: CanArgs, ' \
23
- 'action: CanAction = EXCEPTION_PASS, returnValue: CanArgs'
22
+ COMMON_ARGUMENTS = [
23
+ argument_sdl(
24
+ 'ability: String!',
25
+ 'The ability to check, which the policy answers with a predicate: "update" calls `PostPolicy#update?`.'
26
+ ),
27
+ argument_sdl('injectArgs: Boolean = false', "Pass the field's arguments to the policy method, as its first extra argument."),
28
+ argument_sdl('args: CanArgs', 'Constant values to pass to the policy method, after the injected arguments.'),
29
+ argument_sdl('action: CanAction = EXCEPTION_PASS', 'What to do when the check fails.'),
30
+ argument_sdl('returnValue: CanArgs', 'The value to return, when `action` is RETURN_VALUE.')
31
+ ].freeze
24
32
 
25
33
  TYPE_DEFINITIONS = {
26
34
  'CanArgs' => '"Any constant literal value: https://graphql.github.io/graphql-spec/draft/#sec-Input-Values"' \
@@ -40,8 +48,16 @@ module Lighthouse::GraphQL::DirectiveResolvers
40
48
 
41
49
  def self.type_definitions = TYPE_DEFINITIONS
42
50
 
43
- def self.definition_with(extra = nil)
44
- "directive @#{directive_name}(#{[COMMON_ARGUMENTS, extra].compact.join(', ')}) repeatable on FIELD_DEFINITION"
51
+ # The SDL of a @can* directive: `description`, the arguments they share, then the `extra` ones.
52
+ def self.definition_with(description, extra = [])
53
+ <<~GRAPHQL.chomp
54
+ """
55
+ #{description}
56
+ """
57
+ directive @#{directive_name}(
58
+ #{[*COMMON_ARGUMENTS, *extra].join("\n")}
59
+ ) repeatable on FIELD_DEFINITION
60
+ GRAPHQL
45
61
  end
46
62
 
47
63
  def define_resolver(target_type_class)
@@ -100,7 +116,21 @@ module Lighthouse::GraphQL::DirectiveResolvers
100
116
 
101
117
  class CanFindDirectiveResolver < CanDirectiveResolver
102
118
  def self.directive_name = 'canFind'
103
- def self.definition = definition_with('find: String!, model: String, findOrFail: Boolean = true, scopes: [String!]')
119
+
120
+ def self.definition
121
+ definition_with(<<~TEXT.chomp, [FIND_ARGUMENT, MODEL_ARGUMENT, FIND_OR_FAIL_ARGUMENT, SCOPES_ARGUMENT])
122
+ Check a policy against the models whose primary keys an argument holds, before the field resolves.
123
+ TEXT
124
+ end
125
+
126
+ FIND_ARGUMENT = argument_sdl(
127
+ 'find: String!',
128
+ 'The path of the argument holding the id, or a list of ids, of the models to check: "id", or "input.ids".'
129
+ )
130
+ FIND_OR_FAIL_ARGUMENT = argument_sdl(
131
+ 'findOrFail: Boolean = true',
132
+ 'Fail when an id matches no model. With false, only the models found are checked.'
133
+ )
104
134
 
105
135
  protected
106
136
 
@@ -119,7 +149,13 @@ module Lighthouse::GraphQL::DirectiveResolvers
119
149
 
120
150
  class CanModelDirectiveResolver < CanDirectiveResolver
121
151
  def self.directive_name = 'canModel'
122
- def self.definition = definition_with('model: String')
152
+
153
+ def self.definition
154
+ definition_with(<<~TEXT.chomp, [MODEL_ARGUMENT])
155
+ Check a policy against the model class itself, before the field resolves,
156
+ e.g. `create?` before a @create.
157
+ TEXT
158
+ end
123
159
 
124
160
  protected
125
161
 
@@ -130,7 +166,13 @@ module Lighthouse::GraphQL::DirectiveResolvers
130
166
 
131
167
  class CanQueryDirectiveResolver < CanDirectiveResolver
132
168
  def self.directive_name = 'canQuery'
133
- def self.definition = definition_with('model: String, scopes: [String!]')
169
+
170
+ def self.definition
171
+ definition_with(<<~TEXT.chomp, [MODEL_ARGUMENT, SCOPES_ARGUMENT])
172
+ Check a policy against each model the field's query would return,
173
+ narrowed by the field's argument filters (@eq, @where, ...), before the field resolves.
174
+ TEXT
175
+ end
134
176
 
135
177
  protected
136
178
 
@@ -142,7 +184,13 @@ module Lighthouse::GraphQL::DirectiveResolvers
142
184
 
143
185
  class CanResolvedDirectiveResolver < CanDirectiveResolver
144
186
  def self.directive_name = 'canResolved'
145
- def self.definition = definition_with
187
+
188
+ def self.definition
189
+ definition_with(<<~TEXT.chomp)
190
+ Check a policy against whatever the field resolved to, each item of a list, after it resolves.
191
+ The field runs first: only use it on fields that do not change data.
192
+ TEXT
193
+ end
146
194
 
147
195
  protected
148
196
 
@@ -166,7 +214,12 @@ module Lighthouse::GraphQL::DirectiveResolvers
166
214
 
167
215
  class CanRootDirectiveResolver < CanDirectiveResolver
168
216
  def self.directive_name = 'canRoot'
169
- def self.definition = definition_with
217
+
218
+ def self.definition
219
+ definition_with(<<~TEXT.chomp)
220
+ Check a policy against the parent object of the field, before the field resolves.
221
+ TEXT
222
+ end
170
223
 
171
224
  protected
172
225
 
@@ -9,7 +9,22 @@ require_relative 'builder_applier'
9
9
  # and where/argument filters before counting.
10
10
  class Lighthouse::GraphQL::DirectiveResolvers::CountDirectiveResolver < Lighthouse::GraphQL::DirectiveResolvers::BaseDirectiveResolver
11
11
  def self.directive_name = 'count'
12
- def self.definition = 'directive @count(model: String, relation: String, scopes: [String!]) on FIELD_DEFINITION'
12
+
13
+ def self.definition
14
+ <<~GRAPHQL.chomp
15
+ """
16
+ Return the number of records: of a model's table, or of a relation of the parent.
17
+ The count honors `scopes`, @builder and the field's argument filters (@eq, @where, ...).
18
+ """
19
+ directive @count(
20
+ "The class name of the model whose records to count. Takes precedence over `relation`."
21
+ model: String
22
+ "The relation of the parent to count. Defaults to the field's name, when the parent has it."
23
+ relation: String
24
+ #{SCOPES_ARGUMENT}
25
+ ) on FIELD_DEFINITION
26
+ GRAPHQL
27
+ end
13
28
 
14
29
  def define_resolver(target_type_class)
15
30
  model_name = directive_arg('model')
@@ -11,7 +11,19 @@ require_relative 'base'
11
11
  # name is used as-is); a name that is no class fails the schema build.
12
12
  class Lighthouse::GraphQL::DirectiveResolvers::EventDirectiveResolver < Lighthouse::GraphQL::DirectiveResolvers::BaseDirectiveResolver
13
13
  def self.directive_name = 'event'
14
- def self.definition = 'directive @event(dispatch: String!) repeatable on FIELD_DEFINITION'
14
+
15
+ def self.definition
16
+ <<~GRAPHQL.chomp
17
+ """
18
+ Dispatch an event once the field has resolved. The event is built with the resolved value,
19
+ which is returned unchanged. Nothing is dispatched if the field fails.
20
+ """
21
+ directive @event(
22
+ "The event class, looked up in Config.namespaces[:events]. A fully-qualified name is used as-is."
23
+ dispatch: String!
24
+ ) repeatable on FIELD_DEFINITION
25
+ GRAPHQL
26
+ end
15
27
 
16
28
  def define_resolver(target_type_class)
17
29
  name = directive_arg('dispatch')
@@ -11,7 +11,12 @@ class Lighthouse::GraphQL::DirectiveResolvers::FieldDirectiveResolver < Lighthou
11
11
  Assign a resolver to a field: a class, or a class and a method separated by `@`
12
12
  ("Statistics@users_total"). Without a method, the class resolves, or is called.
13
13
  """
14
- directive @field(resolver: String, class: String) on FIELD_DEFINITION
14
+ directive @field(
15
+ "The resolver: a class, or a class and a method separated by `@`. Required unless `class` is given."
16
+ resolver: String
17
+ "Alias of `resolver`, used when `resolver` is not given."
18
+ class: String
19
+ ) on FIELD_DEFINITION
15
20
  GRAPHQL
16
21
  end
17
22
 
@@ -12,7 +12,19 @@ require_relative 'base'
12
12
  # match is an error, as in PHP Lighthouse; none returns null.
13
13
  class Lighthouse::GraphQL::DirectiveResolvers::FindDirectiveResolver < Lighthouse::GraphQL::DirectiveResolvers::BaseDirectiveResolver
14
14
  def self.directive_name = 'find'
15
- def self.definition = 'directive @find(model: String, scopes: [String!]) on FIELD_DEFINITION'
15
+
16
+ def self.definition
17
+ <<~GRAPHQL.chomp
18
+ """
19
+ Find a single record by the field's argument filters (@eq, @where, ...), or null.
20
+ More than one match is an error. A lookup by `id` alone is batched.
21
+ """
22
+ directive @find(
23
+ #{MODEL_ARGUMENT}
24
+ #{SCOPES_ARGUMENT}
25
+ ) on FIELD_DEFINITION
26
+ GRAPHQL
27
+ end
16
28
 
17
29
  def define_resolver(target_type_class)
18
30
  me = self
@@ -8,7 +8,19 @@ require_relative 'builder_applier'
8
8
  # be combined with @eq/@where to fetch one record by criteria.
9
9
  class Lighthouse::GraphQL::DirectiveResolvers::FirstDirectiveResolver < Lighthouse::GraphQL::DirectiveResolvers::BaseDirectiveResolver
10
10
  def self.directive_name = 'first'
11
- def self.definition = 'directive @first(model: String, scopes: [String!]) on FIELD_DEFINITION'
11
+
12
+ def self.definition
13
+ <<~GRAPHQL.chomp
14
+ """
15
+ Get the first record that matches the field's argument filters (@eq, @where, ...),
16
+ or null. Unlike @find, it does not fail when more than one record matches.
17
+ """
18
+ directive @first(
19
+ #{MODEL_ARGUMENT}
20
+ #{SCOPES_ARGUMENT}
21
+ ) on FIELD_DEFINITION
22
+ GRAPHQL
23
+ end
12
24
 
13
25
  def define_resolver(target_type_class)
14
26
  method_name = "resolve_field_#{@field_def.name}"
@@ -7,7 +7,16 @@ require_relative 'base'
7
7
  # present (per Config.authenticated_user). Mirrors PHP Lighthouse's @guard.
8
8
  class Lighthouse::GraphQL::DirectiveResolvers::GuardDirectiveResolver < Lighthouse::GraphQL::DirectiveResolvers::BaseDirectiveResolver
9
9
  def self.directive_name = 'guard'
10
- def self.definition = 'directive @guard on FIELD_DEFINITION'
10
+
11
+ def self.definition
12
+ <<~GRAPHQL.chomp
13
+ """
14
+ Require an authenticated user (see Config.authenticated_user) before the field resolves,
15
+ else fail with "Unauthenticated.".
16
+ """
17
+ directive @guard on FIELD_DEFINITION
18
+ GRAPHQL
19
+ end
11
20
 
12
21
  def define_resolver(target_type_class)
13
22
  field_name = @field_def.name
@@ -16,7 +16,19 @@ require_relative 'base'
16
16
  # taking no parameters is called without them.
17
17
  class Lighthouse::GraphQL::DirectiveResolvers::MethodDirectiveResolver < Lighthouse::GraphQL::DirectiveResolvers::BaseDirectiveResolver
18
18
  def self.directive_name = 'method'
19
- def self.definition = 'directive @method(name: String) on FIELD_DEFINITION'
19
+
20
+ def self.definition
21
+ <<~GRAPHQL.chomp
22
+ """
23
+ Resolve a field by calling a method on the parent object.
24
+ The field's arguments are passed to the method.
25
+ """
26
+ directive @method(
27
+ "The name of the method to call. Defaults to the field's name in snake_case."
28
+ name: String
29
+ ) on FIELD_DEFINITION
30
+ GRAPHQL
31
+ end
20
32
 
21
33
  def define_resolver(target_type_class)
22
34
  resolver_method = "resolve_field_#{@field_def.name}"
@@ -15,9 +15,31 @@ module Lighthouse::GraphQL::DirectiveResolvers
15
15
  # adds server-side values. On an argument, these directives take
16
16
  # `relation:` and act on that association of the parent instead.
17
17
  class ModelMutationResolver < Lighthouse::GraphQL::DirectiveResolvers::BaseDirectiveResolver
18
- ARGUMENTS = 'model: String, relation: String'
19
18
  LOCATIONS = 'FIELD_DEFINITION | ARGUMENT_DEFINITION | INPUT_FIELD_DEFINITION'
20
19
 
20
+ NESTED_RELATION_ARGUMENT = argument_sdl(
21
+ 'relation: String',
22
+ "On an argument or input field: the association of the parent model that its mutation acts on. Defaults to the argument's name in snake_case."
23
+ )
24
+ IDENTIFYING_COLUMNS_ARGUMENT = argument_sdl(
25
+ 'identifyingColumns: [String!]',
26
+ 'The columns whose values in the input identify an existing model to update. Defaults to the primary key. Must not be empty.'
27
+ )
28
+
29
+ # The SDL of a mutation directive: `description`, then its arguments (the model,
30
+ # the `extra` ones, then the nested relation).
31
+ def self.sdl(description, extra: [])
32
+ arguments = [MODEL_ARGUMENT, *extra, NESTED_RELATION_ARGUMENT]
33
+ <<~GRAPHQL.chomp
34
+ """
35
+ #{description}
36
+ """
37
+ directive @#{directive_name}(
38
+ #{arguments.join("\n")}
39
+ ) on #{LOCATIONS}
40
+ GRAPHQL
41
+ end
42
+
21
43
  def define_resolver(target_type_class)
22
44
  me = self
23
45
  install(target_type_class, lambda do |obj, args, ctx|
@@ -102,7 +124,14 @@ module Lighthouse::GraphQL::DirectiveResolvers
102
124
  # @create — create a model from the field's arguments.
103
125
  class CreateDirectiveResolver < ModelMutationResolver
104
126
  def self.directive_name = 'create'
105
- def self.definition = "directive @create(#{ARGUMENTS}) on #{LOCATIONS}"
127
+
128
+ def self.definition
129
+ sdl(<<~TEXT.chomp)
130
+ Create a model from the field's arguments, through ActiveRecord, so the model's validations apply.
131
+ Nested input on its associations runs as nested mutations.
132
+ On an argument or input field, it creates the record on that association of the parent.
133
+ TEXT
134
+ end
106
135
 
107
136
  protected
108
137
 
@@ -112,7 +141,13 @@ module Lighthouse::GraphQL::DirectiveResolvers
112
141
  # @createMany — create one model per input in the field's single list argument.
113
142
  class CreateManyDirectiveResolver < ModelMutationResolver
114
143
  def self.directive_name = 'createMany'
115
- def self.definition = "directive @createMany(#{ARGUMENTS}) on #{LOCATIONS}"
144
+
145
+ def self.definition
146
+ sdl(<<~TEXT.chomp)
147
+ Create many models, one per input of the field's single list argument.
148
+ If any is invalid nothing is saved, and the errors of all are reported.
149
+ TEXT
150
+ end
116
151
 
117
152
  protected
118
153
 
@@ -124,7 +159,14 @@ module Lighthouse::GraphQL::DirectiveResolvers
124
159
  # @update — find a model by its primary key argument and update it.
125
160
  class UpdateDirectiveResolver < ModelMutationResolver
126
161
  def self.directive_name = 'update'
127
- def self.definition = "directive @update(#{ARGUMENTS}) on #{LOCATIONS}"
162
+
163
+ def self.definition
164
+ sdl(<<~TEXT.chomp)
165
+ Update a model found by the primary key in the field's arguments, through ActiveRecord,
166
+ so the model's validations apply. Nested input on its associations runs as nested mutations.
167
+ On an argument or input field, it updates the record on that association of the parent.
168
+ TEXT
169
+ end
128
170
 
129
171
  protected
130
172
 
@@ -134,7 +176,13 @@ module Lighthouse::GraphQL::DirectiveResolvers
134
176
  # @updateMany — update one model per input (each carrying its primary key).
135
177
  class UpdateManyDirectiveResolver < ModelMutationResolver
136
178
  def self.directive_name = 'updateMany'
137
- def self.definition = "directive @updateMany(#{ARGUMENTS}) on #{LOCATIONS}"
179
+
180
+ def self.definition
181
+ sdl(<<~TEXT.chomp)
182
+ Update many models, one per input of the field's single list argument, each carrying its primary key.
183
+ If any is invalid nothing is saved, and the errors of all are reported.
184
+ TEXT
185
+ end
138
186
 
139
187
  protected
140
188
 
@@ -147,7 +195,13 @@ module Lighthouse::GraphQL::DirectiveResolvers
147
195
  # else primary key), or create it.
148
196
  class UpsertDirectiveResolver < ModelMutationResolver
149
197
  def self.directive_name = 'upsert'
150
- def self.definition = "directive @upsert(#{ARGUMENTS}, identifyingColumns: [String!]) on #{LOCATIONS}"
198
+
199
+ def self.definition
200
+ sdl(<<~TEXT.chomp, extra: [IDENTIFYING_COLUMNS_ARGUMENT])
201
+ Update the model the arguments identify (by `identifyingColumns`, else the primary key), or create it.
202
+ Saved through ActiveRecord, so the model's validations apply.
203
+ TEXT
204
+ end
151
205
 
152
206
  def define_resolver(target_type_class)
153
207
  validate_identifying_columns!
@@ -165,7 +219,13 @@ module Lighthouse::GraphQL::DirectiveResolvers
165
219
  # @upsertMany — @upsert for each input in the field's single list argument.
166
220
  class UpsertManyDirectiveResolver < ModelMutationResolver
167
221
  def self.directive_name = 'upsertMany'
168
- def self.definition = "directive @upsertMany(#{ARGUMENTS}, identifyingColumns: [String!]) on #{LOCATIONS}"
222
+
223
+ def self.definition
224
+ sdl(<<~TEXT.chomp, extra: [IDENTIFYING_COLUMNS_ARGUMENT])
225
+ Upsert many models, one per input of the field's single list argument.
226
+ If any is invalid nothing is saved, and the errors of all are reported.
227
+ TEXT
228
+ end
169
229
 
170
230
  def define_resolver(target_type_class)
171
231
  validate_identifying_columns!
@@ -194,7 +254,7 @@ module Lighthouse::GraphQL::DirectiveResolvers
194
254
  # to the data, as PHP Lighthouse does; the others are still modified.
195
255
  def mutate(model, _obj, args, ctx)
196
256
  args = Lighthouse::Support::Arguments.shallow(args)
197
- raise ::GraphQL::ExecutionError, WOULD_MODIFY_ALL unless filtered?(args)
257
+ raise ::GraphQL::ExecutionError, WOULD_MODIFY_ALL unless filtering?(args)
198
258
 
199
259
  records = apply_where_filters(records_of(model), args, ctx).to_a
200
260
  records.each do |record|
@@ -212,20 +272,19 @@ module Lighthouse::GraphQL::DirectiveResolvers
212
272
  def modify(_record)
213
273
  raise NotImplementedError
214
274
  end
215
-
216
- def filtered?(args)
217
- registry = Lighthouse::DirectiveRegistry.default
218
- (@field_def.ast_node.arguments || []).any? do |argument|
219
- args.key?(argument.name.underscore.to_sym) && argument.directives.any? { |d| registry.arg_builder_class(d.name) }
220
- end
221
- end
222
275
  end
223
276
 
224
277
  # @delete — destroy the models the field's argument filters select
225
278
  # (@whereKey, @eq, ...), running their callbacks, and return them.
226
279
  class DeleteDirectiveResolver < ModifyModelsResolver
227
280
  def self.directive_name = 'delete'
228
- def self.definition = "directive @delete(#{ARGUMENTS}, scopes: [String!]) on #{LOCATIONS}"
281
+
282
+ def self.definition
283
+ sdl(<<~TEXT.chomp, extra: [SCOPES_ARGUMENT])
284
+ Delete the models the field's argument filters (@whereKey, @eq, ...) select, running their callbacks,
285
+ and return them: a list for a list field, else the first or null. Refuses to run without a filter argument.
286
+ TEXT
287
+ end
229
288
 
230
289
  protected
231
290
 
@@ -18,8 +18,23 @@ class Lighthouse::GraphQL::DirectiveResolvers::PaginateDirectiveResolver < Light
18
18
  def self.directive_name = 'paginate'
19
19
 
20
20
  def self.definition
21
- 'directive @paginate(type: PaginateType = PAGINATOR, model: String, scopes: [String!], ' \
22
- 'defaultCount: Int, maxCount: Int) on FIELD_DEFINITION'
21
+ <<~GRAPHQL.chomp
22
+ """
23
+ Query multiple model entries as a paginated list.
24
+ The query is the model's, narrowed by `scopes`, @builder and the field's argument filters
25
+ (@eq, @where, @orderBy, ...). On a nested field, it pages the parent's association of the same name.
26
+ """
27
+ directive @paginate(
28
+ "Which pagination style to use."
29
+ type: PaginateType = PAGINATOR
30
+ #{MODEL_ARGUMENT}
31
+ #{SCOPES_ARGUMENT}
32
+ "The page size when the client omits `first`. Defaults to Config.pagination_default_count."
33
+ defaultCount: Int
34
+ "The most records the client may ask for with `first`; null for no limit. Defaults to Config.pagination_max_count."
35
+ maxCount: Int
36
+ ) on FIELD_DEFINITION
37
+ GRAPHQL
23
38
  end
24
39
 
25
40
  def self.type_definitions
@@ -7,7 +7,20 @@ require_relative 'base'
7
7
  # of the GraphQL field name.
8
8
  class Lighthouse::GraphQL::DirectiveResolvers::RenameDirectiveResolver < Lighthouse::GraphQL::DirectiveResolvers::BaseDirectiveResolver
9
9
  def self.directive_name = 'rename'
10
- def self.definition = 'directive @rename(attribute: String!) on FIELD_DEFINITION | ARGUMENT_DEFINITION | INPUT_FIELD_DEFINITION'
10
+
11
+ def self.definition
12
+ <<~GRAPHQL.chomp
13
+ """
14
+ Use another attribute than the name of the field, argument or input field.
15
+ On a field, its value is read from that attribute of the parent object;
16
+ on an argument, @create and @update write it to that attribute of the model.
17
+ """
18
+ directive @rename(
19
+ "The name of the attribute, in the model or the parent object."
20
+ attribute: String!
21
+ ) on FIELD_DEFINITION | ARGUMENT_DEFINITION | INPUT_FIELD_DEFINITION
22
+ GRAPHQL
23
+ end
11
24
 
12
25
  def define_resolver(target_type_class)
13
26
  method_name = "resolve_field_#{@field_def.name}"
@@ -20,7 +20,19 @@ require_relative 'base'
20
20
  # each request, so its hooks (`subscribe`, `update`, ...) run as usual.
21
21
  class Lighthouse::GraphQL::DirectiveResolvers::SubscriptionDirectiveResolver < Lighthouse::GraphQL::DirectiveResolvers::BaseDirectiveResolver
22
22
  def self.directive_name = 'subscription'
23
- def self.definition = 'directive @subscription(class: String!) on FIELD_DEFINITION'
23
+
24
+ def self.definition
25
+ <<~GRAPHQL.chomp
26
+ """
27
+ Reference a class to handle a field of the Subscription type: a GraphQL::Schema::Subscription.
28
+ Without it, the field resolves to the class named after it, in Config.namespaces[:subscriptions].
29
+ """
30
+ directive @subscription(
31
+ "The subscription class, looked up in Config.namespaces[:subscriptions]. A fully-qualified name is used as-is."
32
+ class: String!
33
+ ) on FIELD_DEFINITION
34
+ GRAPHQL
35
+ end
24
36
 
25
37
  def define_resolver(target_type_class)
26
38
  unless @opts[:root_kind] == :subscriptions