lighthouse-graphql 0.7.1 → 0.7.2

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 (40) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +22 -1
  3. data/docs/getting-started.md +44 -11
  4. data/lib/lighthouse/ast_builder.rb +4 -1
  5. data/lib/lighthouse/cache_control.rb +14 -2
  6. data/lib/lighthouse/complexity.rb +11 -1
  7. data/lib/lighthouse/directive_resolvers/aggregate_resolver.rb +17 -1
  8. data/lib/lighthouse/directive_resolvers/all_resolver.rb +13 -1
  9. data/lib/lighthouse/directive_resolvers/association_resolvers.rb +65 -9
  10. data/lib/lighthouse/directive_resolvers/auth_resolver.rb +10 -1
  11. data/lib/lighthouse/directive_resolvers/base.rb +18 -0
  12. data/lib/lighthouse/directive_resolvers/broadcast_resolver.rb +12 -1
  13. data/lib/lighthouse/directive_resolvers/cache_resolvers.rb +28 -3
  14. data/lib/lighthouse/directive_resolvers/can_resolvers.rb +62 -9
  15. data/lib/lighthouse/directive_resolvers/count_resolver.rb +16 -1
  16. data/lib/lighthouse/directive_resolvers/event_resolver.rb +13 -1
  17. data/lib/lighthouse/directive_resolvers/field_resolver.rb +6 -1
  18. data/lib/lighthouse/directive_resolvers/find_resolver.rb +13 -1
  19. data/lib/lighthouse/directive_resolvers/first_resolver.rb +13 -1
  20. data/lib/lighthouse/directive_resolvers/guard_resolver.rb +10 -1
  21. data/lib/lighthouse/directive_resolvers/method_resolver.rb +13 -1
  22. data/lib/lighthouse/directive_resolvers/model_mutation_resolver.rb +74 -8
  23. data/lib/lighthouse/directive_resolvers/paginate_resolver.rb +17 -2
  24. data/lib/lighthouse/directive_resolvers/rename_resolver.rb +14 -1
  25. data/lib/lighthouse/directive_resolvers/subscription_resolver.rb +13 -1
  26. data/lib/lighthouse/directive_resolvers/validator_resolver.rb +13 -1
  27. data/lib/lighthouse/directives/arguments/base.rb +18 -0
  28. data/lib/lighthouse/directives/arguments/filters.rb +16 -7
  29. data/lib/lighthouse/directives/definitions.rb +43 -6
  30. data/lib/lighthouse/document_ast.rb +6 -0
  31. data/lib/lighthouse/enum_directive.rb +6 -1
  32. data/lib/lighthouse/feature_directive.rb +13 -1
  33. data/lib/lighthouse/graphql/version.rb +1 -1
  34. data/lib/lighthouse/graphql_ruby_patches.rb +26 -2
  35. data/lib/lighthouse/ide_helper.rb +7 -6
  36. data/lib/lighthouse/scalar_coercion.rb +4 -1
  37. data/lib/lighthouse/tasks/lighthouse.rake +8 -0
  38. data/lib/lighthouse/type_resolution.rb +8 -2
  39. data/sig/lighthouse/graphql.rbs +1 -0
  40. metadata +1 -1
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 504295e8c73043df4b45703bb304b02205a40298e5bc686eb7d3b93dd678478e
4
- data.tar.gz: f5e1bc31e13856b2f636978eaed1c8d00c5fe6246bba46f4fad513d8ee247dfc
3
+ metadata.gz: 30f0e741c78c61751024d75f1b7599e5e8e1e3b2bc426a48f7b6a89c86eacf19
4
+ data.tar.gz: 45e1282efbb6115e4cf4931fd51a05b85cc8d096d204aba819d90228766da3a7
5
5
  SHA512:
6
- metadata.gz: 5aa2a3bcb218dc305b68cbb0d2ac1b437fdcd801a0965bc0e9c69de994b8028febb7c6a46fe2edff8e4b39d386b94369a63d603f6899fe1b9065d1a7196fd750
7
- data.tar.gz: 1dd8ef4b1426c9c4555a087da98aaee17cdbbf3133bd375ee6e2d83e738a4911d5e091545b7b65a3262bf823a8bd7f5e034943cf2124077a9d54c42930ee0b7a
6
+ metadata.gz: a13e0fad7027bf2201b63f1543b95808fd63bc7f0ff0f71b9361c42e72f808b4e6475ac9f82298257884c28ecb878924d2ba7a0b1aa4c2186c049a626962c416
7
+ data.tar.gz: 5f84257bfde8cf780b224f39615b4c8a0cff520479b97e7e106859084e390db0f9fe5a24fff0e2573609e46129c2b43d210a8fa36c3f972da67c1b7f2b3268cd
data/CHANGELOG.md CHANGED
@@ -6,6 +6,26 @@ project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
6
6
 
7
7
  ## [Unreleased]
8
8
 
9
+ ## [0.7.2] - 2026-10-29
10
+
11
+ ### Added
12
+
13
+ - `bin/rails lighthouse:print_schema` prints the final schema, as PHP Lighthouse's
14
+ `lighthouse:print-schema` does: to stdout, from the current configuration
15
+ (`SCHEMA=AppSchema` names another schema). Redirect it to keep it:
16
+ `bin/rails lighthouse:print_schema > generated.graphql`.
17
+
18
+ ### Changed
19
+
20
+ - **`schema-directives.graphql` documents everything.** Every directive, argument, enum value
21
+ and input field Lighthouse defines carries a description, so the IDE shows it on hover and in
22
+ autocomplete. A spec fails when a new one is added without.
23
+ - `programmatic-types.graphql` always declares the `_` placeholder scalar (unless your SDL
24
+ declares it), whether or not the SDL uses it yet, so the IDE never reports `Unknown type "_"`
25
+ the moment you write `where: _ @whereConditions`.
26
+ - The `_` placeholder exists only for the IDE: a `scalar _` in your SDL is dropped once the
27
+ schema builds, so the executable schema (and its introspection) has no `_` type.
28
+
9
29
  ## [0.7.1] - 2026-10-18
10
30
 
11
31
  ### Added
@@ -681,7 +701,8 @@ had been running inside a private monorepo as a path gem before being extracted.
681
701
  - Config-driven extension seams: `Lighthouse.configure`, `resolver_namespaces`,
682
702
  `on_error`, and `DirectiveRegistry.register` for app-defined directives.
683
703
 
684
- [Unreleased]: https://github.com/Vaz-Innovation/lighthouse-graphql/compare/v0.7.1...HEAD
704
+ [Unreleased]: https://github.com/Vaz-Innovation/lighthouse-graphql/compare/v0.7.2...HEAD
705
+ [0.7.2]: https://github.com/Vaz-Innovation/lighthouse-graphql/compare/v0.7.1...v0.7.2
685
706
  [0.7.1]: https://github.com/Vaz-Innovation/lighthouse-graphql/compare/v0.7.0...v0.7.1
686
707
  [0.7.0]: https://github.com/Vaz-Innovation/lighthouse-graphql/compare/v0.6.0...v0.7.0
687
708
  [0.6.0]: https://github.com/Vaz-Innovation/lighthouse-graphql/compare/v0.5.0...v0.6.0
@@ -5,6 +5,12 @@ GraphQL endpoint.
5
5
 
6
6
  ## Install
7
7
 
8
+ Lighthouse is built on [graphql-ruby](https://graphql-ruby.org), and the two are
9
+ set up together, in three commands:
10
+
11
+ **The gems.** `lighthouse-graphql` depends on `graphql ~> 2.5`, so adding it
12
+ installs graphql-ruby too:
13
+
8
14
  ```ruby
9
15
  # Gemfile
10
16
  gem 'lighthouse-graphql'
@@ -14,19 +20,36 @@ gem 'lighthouse-graphql'
14
20
  bundle install
15
21
  ```
16
22
 
17
- Runtime dependencies (`graphql ~> 2.5`, `activesupport`) come with the gem. If you
18
- want federation, add `apollo-federation` to your app — it is intentionally **not**
19
- a hard dependency of Lighthouse so non-federated apps stay lean.
23
+ You can also list `gem 'graphql'` yourself, to pin its version. On graphql 2.5, keep
24
+ the `json` gem below 3: graphql 2.5 calls `JSON.generate` with an option json 3
25
+ removed (graphql 2.6 no longer does). If you want federation, add `apollo-federation`
26
+ to your app — it is intentionally **not** a hard dependency of Lighthouse so
27
+ non-federated apps stay lean.
20
28
 
21
- ## The install generator
29
+ **graphql-ruby's install** (optional). This writes the schema class, the base
30
+ classes (`Types::BaseObject`, ...), the root types and the controller. Choose its
31
+ options here, as for any graphql-ruby app (`--relay`, `--batch`, `--api`,
32
+ `--schema=ApiSchema`, `--skip-mutation-root-type`, ...):
33
+
34
+ ```shell
35
+ bin/rails generate graphql:install
36
+ ```
37
+
38
+ **Lighthouse's install.** It adapts what graphql-ruby wrote and adds its own files
39
+ (see below). If you skipped graphql-ruby's install, it runs `graphql:install` for you,
40
+ with graphql-ruby's defaults, so the two commands are never both required:
22
41
 
23
42
  ```shell
24
43
  bin/rails generate lighthouse:install
25
44
  ```
26
45
 
27
- does steps 1–5 below for you. It builds on graphql-ruby's own install,
28
- `rails g graphql:install`, with whichever of its options the app chose (`--relay`,
29
- `--batch`, `--api`, ...). When the app has no graphql-ruby schema class yet, it runs
46
+ Run `graphql:install` yourself only to pass it options; Lighthouse then keeps them.
47
+
48
+ ## The install generator
49
+
50
+ `bin/rails generate lighthouse:install` does steps 1–5 below for you. It builds on
51
+ graphql-ruby's own install, `rails g graphql:install`, with whichever of its options
52
+ the app chose (`--relay`, `--batch`, `--api`, ...). When the app has no graphql-ruby schema class yet, it runs
30
53
  `graphql:install` first, with graphql-ruby's defaults. Then it adapts what
31
54
  graphql-ruby wrote, and adds Lighthouse's own:
32
55
 
@@ -303,10 +326,11 @@ It writes two files:
303
326
  - **`programmatic-types.graphql`** — the types Lighthouse adds to the executable
304
327
  schema: `<Type>Paginator`, `<Type>SimplePaginator`, `<Type>Connection`/`Edge`,
305
328
  `PaginatorInfo`, `SimplePaginatorInfo`, `PageInfo`, the `@whereConditions` and
306
- `@orderBy` inputs and enums, and the `_` placeholder scalar (without it, the
307
- IDE reports `Unknown type "_"`). It leaves out every type the SDL or
308
- `schema-directives.graphql` defines, because graphql-js, which the IDE plugins
309
- use, rejects a type defined twice.
329
+ `@orderBy` inputs and enums, and the `_` placeholder scalar (always declared,
330
+ even before the SDL uses it; without it, the IDE reports `Unknown type "_"`).
331
+ It is for the IDE only: the schema Lighthouse builds has no `_` type. It leaves
332
+ out every type the SDL or `schema-directives.graphql` defines, because
333
+ graphql-js, which the IDE plugins use, rejects a type defined twice.
310
334
 
311
335
  Point your IDE's [graphql-config](https://the-guild.dev/graphql/config) at them
312
336
  next to your SDL — the install generator writes this `graphql.config.yml`:
@@ -324,6 +348,15 @@ VS Code. The files are derived from your schema, so the generator adds them to
324
348
  registering a directive. The IDE reads every `.graphql` file the glob matches, as
325
349
  one schema: it does not follow `#import`.
326
350
 
351
+ To see the schema clients get, with every type Lighthouse generated and the
352
+ fields rewritten (`users { data { … } }`), print it. The task writes the SDL to
353
+ stdout and nothing else, so redirect it to keep it:
354
+
355
+ ```shell
356
+ bin/rails lighthouse:print_schema # AppSchema
357
+ SCHEMA=Admin::Schema bin/rails lighthouse:print_schema > generated.graphql
358
+ ```
359
+
327
360
  > The IDE reads fields as you wrote them: `users: [User!]! @paginate` still looks
328
361
  > like a list to it, although clients query `users { data { … } }`. Field
329
362
  > rewrites are not something an extra file can express.
@@ -11,7 +11,8 @@
11
11
  # 4. The argument manipulators: each argument directive whose class includes
12
12
  # Contracts::ArgManipulator rewrites its argument (@whereConditions,
13
13
  # @whereHasConditions, @orderBy turn `_` into the input types they generate).
14
- # 5. The definitions of directives the generated types use (`@enum`).
14
+ # 5. `scalar _`, if the SDL declares it for the IDE, dropped: nothing is left of the placeholder.
15
+ # 6. The definitions of directives the generated types use (`@enum`).
15
16
  #
16
17
  # Returns the manipulated SDL; ManipulateAST listeners then see its document.
17
18
  module Lighthouse::GraphQL::ASTBuilder
@@ -48,6 +49,8 @@ module Lighthouse::GraphQL::ASTBuilder
48
49
 
49
50
  document_ast = Lighthouse::GraphQL::DocumentAST.from_source(registry.manipulate_sdl(document_ast.to_sdl))
50
51
  apply_arg_manipulators(document_ast, registry)
52
+ # `scalar _` is for the IDE (IdeHelper); the executable schema has no placeholder.
53
+ document_ast.remove_type(Lighthouse::GraphQL::Directives::GeneratedTypes::PLACEHOLDER)
51
54
 
52
55
  Lighthouse::GraphQL::SchemaGenerator.inject_directive_definitions(document_ast.to_sdl)
53
56
  end
@@ -21,8 +21,20 @@ module Lighthouse::GraphQL::CacheControl
21
21
  # Arguments with a default are nullable, not `Type! = default` as in PHP: graphql-ruby
22
22
  # 2.5 does not fill in a directive argument's default, so a non-null one would be
23
23
  # refused wherever it is left out. Left out or null, it takes its default.
24
- DEFINITION = 'directive @cacheControl(maxAge: Int = 0, scope: CacheControlScope = PUBLIC, ' \
25
- 'inheritMaxAge: Boolean = false) on FIELD_DEFINITION | OBJECT | INTERFACE | UNION'
24
+ DEFINITION = <<~GRAPHQL.chomp
25
+ """
26
+ Set the HTTP Cache-Control header of the response, from the fields and types a query selects.
27
+ The response may be cached for the lowest maxAge among them, and is private if any scope is.
28
+ """
29
+ directive @cacheControl(
30
+ "The maximum amount of time, in seconds, the field's value may be cached. 0 means `no-cache`."
31
+ maxAge: Int = 0
32
+ "Who a cached response may be shared with."
33
+ scope: CacheControlScope = PUBLIC
34
+ "Use the maxAge of the parent field. The `maxAge` argument is ignored."
35
+ inheritMaxAge: Boolean = false
36
+ ) on FIELD_DEFINITION | OBJECT | INTERFACE | UNION
37
+ GRAPHQL
26
38
 
27
39
  TYPE_DEFINITIONS = {
28
40
  'CacheControlScope' => <<~GRAPHQL.chomp
@@ -28,7 +28,17 @@
28
28
  # Analyzer scores each query for BuildExtensionsResponse#query_complexity while
29
29
  # something listens to that event.
30
30
  module Lighthouse::GraphQL::Complexity
31
- DEFINITION = 'directive @complexity(resolver: String) on FIELD_DEFINITION'
31
+ DEFINITION = <<~GRAPHQL.chomp
32
+ """
33
+ Customize the cost of a field in the complexity score of a query, which graphql-ruby checks
34
+ against the schema's `max_complexity`. Without a resolver, the field costs 1 plus its selection,
35
+ once per item asked for on a paginated field.
36
+ """
37
+ directive @complexity(
38
+ "The analyzer class that gives the cost, looked up in Config.namespaces[:analyzers]. It includes Lighthouse::GraphQL::ComplexityAnalyzer and declares `complexity`."
39
+ resolver: String
40
+ ) on FIELD_DEFINITION
41
+ GRAPHQL
32
42
 
33
43
  CONTEXT_KEY = :lighthouse_query_complexity
34
44
 
@@ -16,7 +16,23 @@ class Lighthouse::GraphQL::DirectiveResolvers::AggregateDirectiveResolver < Ligh
16
16
  }.freeze
17
17
 
18
18
  def self.definition
19
- 'directive @aggregate(function: String!, column: String, model: String, relation: String) on FIELD_DEFINITION'
19
+ <<~GRAPHQL.chomp
20
+ """
21
+ Return an aggregate of a column over the records of a model, or of a relation of the parent.
22
+ The records are narrowed by the field's argument filters (@eq, @where, ...).
23
+ An unknown function, or a failing aggregation, answers null.
24
+ """
25
+ directive @aggregate(
26
+ "The aggregate to compute: SUM, AVG, MIN, MAX or COUNT (case-insensitive)."
27
+ function: String!
28
+ "The column to aggregate. COUNT does not use it."
29
+ column: String
30
+ "The class name of the model whose records to aggregate. Takes precedence over `relation`."
31
+ model: String
32
+ "The relation of the parent to aggregate over."
33
+ relation: String
34
+ ) on FIELD_DEFINITION
35
+ GRAPHQL
20
36
  end
21
37
 
22
38
  def define_resolver(target_type_class)
@@ -5,7 +5,19 @@ require_relative 'builder_applier'
5
5
 
6
6
  class Lighthouse::GraphQL::DirectiveResolvers::AllDirectiveResolver < Lighthouse::GraphQL::DirectiveResolvers::BaseDirectiveResolver
7
7
  def self.directive_name = 'all'
8
- def self.definition = 'directive @all(model: String, scopes: [String!]) on FIELD_DEFINITION'
8
+
9
+ def self.definition
10
+ <<~GRAPHQL.chomp
11
+ """
12
+ Get a collection of models as the field result: all the model's records,
13
+ narrowed by `scopes`, @builder and the field's argument filters (@eq, @where, ...).
14
+ """
15
+ directive @all(
16
+ #{MODEL_ARGUMENT}
17
+ #{SCOPES_ARGUMENT}
18
+ ) on FIELD_DEFINITION
19
+ GRAPHQL
20
+ end
9
21
 
10
22
  def define_resolver(target_type_class)
11
23
  model_class = constantize_model(extract_model_name || @field_def.type.unwrap.graphql_name)
@@ -20,6 +20,21 @@ module Lighthouse::GraphQL::DirectiveResolvers
20
20
 
21
21
  def self.collection? = false
22
22
 
23
+ # The directive's SDL: `description`, then the arguments of a relationship —
24
+ # and, on a collection, the pagination ones.
25
+ def self.definition(name = directive_name, description = self::DESCRIPTION)
26
+ arguments = [RELATION_ARGUMENT, SCOPES_ARGUMENT]
27
+ arguments += PAGINATION_ARGUMENTS if collection?
28
+ <<~GRAPHQL.chomp
29
+ """
30
+ #{description}
31
+ """
32
+ directive @#{name}(
33
+ #{arguments.join("\n")}
34
+ ) on FIELD_DEFINITION
35
+ GRAPHQL
36
+ end
37
+
23
38
  def define_resolver(target_type_class)
24
39
  me = self
25
40
  install(target_type_class, lambda do |obj, args, ctx|
@@ -116,49 +131,90 @@ module Lighthouse::GraphQL::DirectiveResolvers
116
131
  end
117
132
  end
118
133
 
119
- COLLECTION_ARGUMENTS = 'relation: String, scopes: [String!], type: PaginateType, defaultCount: Int, maxCount: Int'
134
+ PAGINATION_ARGUMENTS = [
135
+ BaseDirectiveResolver.argument_sdl(
136
+ 'type: PaginateType',
137
+ 'How to paginate the list: PAGINATOR, SIMPLE or CONNECTION. Without it, the whole list is returned.'
138
+ ),
139
+ BaseDirectiveResolver.argument_sdl(
140
+ 'defaultCount: Int',
141
+ 'The page size when the client omits `first`. Defaults to Config.pagination_default_count.'
142
+ ),
143
+ BaseDirectiveResolver.argument_sdl(
144
+ 'maxCount: Int',
145
+ 'The most records the client may ask for with `first`; null for no limit. Defaults to Config.pagination_max_count.'
146
+ )
147
+ ].freeze
120
148
 
121
149
  class HasManyDirectiveResolver < AssociationDirectiveResolver
122
150
  def self.collection? = true
123
151
  def self.directive_name = 'hasMany'
124
- def self.definition = "directive @hasMany(#{COLLECTION_ARGUMENTS}) on FIELD_DEFINITION"
152
+ DESCRIPTION = <<~TEXT.chomp
153
+ Resolve a one-to-many association of the parent (`has_many`) as a list,
154
+ batch-loaded so that listing it for many parents is not an N+1.
155
+ With `type`, the list is paginated.
156
+ TEXT
125
157
  end
126
158
 
127
159
  class BelongsToManyDirectiveResolver < AssociationDirectiveResolver
128
160
  def self.collection? = true
129
161
  def self.directive_name = 'belongsToMany'
130
- def self.definition = "directive @belongsToMany(#{COLLECTION_ARGUMENTS}) on FIELD_DEFINITION"
162
+ DESCRIPTION = <<~TEXT.chomp
163
+ Resolve a many-to-many association of the parent (`has_and_belongs_to_many`) as a list,
164
+ batch-loaded so that listing it for many parents is not an N+1.
165
+ With `type`, the list is paginated.
166
+ TEXT
131
167
  end
132
168
 
133
169
  class MorphManyDirectiveResolver < AssociationDirectiveResolver
134
170
  def self.collection? = true
135
171
  def self.directive_name = 'morphMany'
136
- def self.definition = "directive @morphMany(#{COLLECTION_ARGUMENTS}) on FIELD_DEFINITION"
172
+ DESCRIPTION = <<~TEXT.chomp
173
+ Resolve a polymorphic one-to-many association of the parent (`has_many ..., as:`) as a list,
174
+ batch-loaded so that listing it for many parents is not an N+1.
175
+ With `type`, the list is paginated.
176
+ TEXT
137
177
  end
138
178
 
139
179
  class MorphToManyDirectiveResolver < AssociationDirectiveResolver
140
180
  def self.collection? = true
141
181
  def self.directive_name = 'morphToMany'
142
- def self.definition = "directive @morphToMany(#{COLLECTION_ARGUMENTS}) on FIELD_DEFINITION"
182
+ DESCRIPTION = <<~TEXT.chomp
183
+ Resolve a polymorphic many-to-many association of the parent as a list,
184
+ batch-loaded so that listing it for many parents is not an N+1.
185
+ With `type`, the list is paginated.
186
+ TEXT
143
187
  end
144
188
 
145
189
  class HasOneDirectiveResolver < AssociationDirectiveResolver
146
190
  def self.directive_name = 'hasOne'
147
- def self.definition = 'directive @hasOne(relation: String, scopes: [String!]) on FIELD_DEFINITION'
191
+ DESCRIPTION = <<~TEXT.chomp
192
+ Resolve a one-to-one association of the parent (`has_one`),
193
+ batch-loaded so that loading it for many parents is not an N+1.
194
+ TEXT
148
195
  end
149
196
 
150
197
  class MorphOneDirectiveResolver < AssociationDirectiveResolver
151
198
  def self.directive_name = 'morphOne'
152
- def self.definition = 'directive @morphOne(relation: String, scopes: [String!]) on FIELD_DEFINITION'
199
+ DESCRIPTION = <<~TEXT.chomp
200
+ Resolve a polymorphic one-to-one association of the parent (`has_one ..., as:`),
201
+ batch-loaded so that loading it for many parents is not an N+1.
202
+ TEXT
153
203
  end
154
204
 
155
205
  class BelongsToDirectiveResolver < AssociationDirectiveResolver
156
206
  def self.directive_name = 'belongsTo'
157
- def self.definition = 'directive @belongsTo(relation: String, scopes: [String!]) on FIELD_DEFINITION'
207
+ DESCRIPTION = <<~TEXT.chomp
208
+ Resolve the inverse of a one-to-one or one-to-many association (`belongs_to`),
209
+ batch-loaded so that loading it for many parents is not an N+1.
210
+ TEXT
158
211
  end
159
212
 
160
213
  class MorphToDirectiveResolver < AssociationDirectiveResolver
161
214
  def self.directive_name = 'morphTo'
162
- def self.definition = 'directive @morphTo(relation: String, scopes: [String!]) on FIELD_DEFINITION'
215
+ DESCRIPTION = <<~TEXT.chomp
216
+ Resolve a polymorphic inverse association of the parent (`belongs_to ..., polymorphic: true`),
217
+ batch-loaded so that loading it for many parents is not an N+1.
218
+ TEXT
163
219
  end
164
220
  end
@@ -2,7 +2,16 @@
2
2
 
3
3
  class Lighthouse::GraphQL::DirectiveResolvers::AuthDirectiveResolver < Lighthouse::GraphQL::DirectiveResolvers::BaseDirectiveResolver
4
4
  def self.directive_name = 'auth'
5
- def self.definition = 'directive @auth on FIELD_DEFINITION'
5
+
6
+ def self.definition
7
+ <<~GRAPHQL.chomp
8
+ """
9
+ Require an authenticated user (`context[:current_user]`) before the field resolves,
10
+ else fail with "Unauthenticated.". @guard is the configurable equivalent.
11
+ """
12
+ directive @auth on FIELD_DEFINITION
13
+ GRAPHQL
14
+ end
6
15
 
7
16
  def define_resolver(target_type_class)
8
17
  inner = original_resolver(target_type_class)
@@ -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
@@ -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')