lighthouse-graphql 0.7.0 → 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 (45) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +34 -1
  3. data/docs/generators.md +1 -1
  4. data/docs/getting-started.md +45 -12
  5. data/docs/relay.md +52 -3
  6. data/lib/generators/lighthouse/install/graphql_ruby_install.rb +14 -0
  7. data/lib/generators/lighthouse/install/install_generator.rb +15 -1
  8. data/lib/generators/lighthouse/install/templates/schema.graphql.tt +30 -0
  9. data/lib/lighthouse/ast_builder.rb +4 -1
  10. data/lib/lighthouse/cache_control.rb +14 -2
  11. data/lib/lighthouse/complexity.rb +11 -1
  12. data/lib/lighthouse/directive_resolvers/aggregate_resolver.rb +17 -1
  13. data/lib/lighthouse/directive_resolvers/all_resolver.rb +13 -1
  14. data/lib/lighthouse/directive_resolvers/association_resolvers.rb +65 -9
  15. data/lib/lighthouse/directive_resolvers/auth_resolver.rb +10 -1
  16. data/lib/lighthouse/directive_resolvers/base.rb +18 -0
  17. data/lib/lighthouse/directive_resolvers/broadcast_resolver.rb +12 -1
  18. data/lib/lighthouse/directive_resolvers/cache_resolvers.rb +28 -3
  19. data/lib/lighthouse/directive_resolvers/can_resolvers.rb +62 -9
  20. data/lib/lighthouse/directive_resolvers/count_resolver.rb +16 -1
  21. data/lib/lighthouse/directive_resolvers/event_resolver.rb +13 -1
  22. data/lib/lighthouse/directive_resolvers/field_resolver.rb +6 -1
  23. data/lib/lighthouse/directive_resolvers/find_resolver.rb +13 -1
  24. data/lib/lighthouse/directive_resolvers/first_resolver.rb +13 -1
  25. data/lib/lighthouse/directive_resolvers/guard_resolver.rb +10 -1
  26. data/lib/lighthouse/directive_resolvers/method_resolver.rb +13 -1
  27. data/lib/lighthouse/directive_resolvers/model_mutation_resolver.rb +74 -8
  28. data/lib/lighthouse/directive_resolvers/paginate_resolver.rb +17 -2
  29. data/lib/lighthouse/directive_resolvers/rename_resolver.rb +14 -1
  30. data/lib/lighthouse/directive_resolvers/subscription_resolver.rb +13 -1
  31. data/lib/lighthouse/directive_resolvers/validator_resolver.rb +13 -1
  32. data/lib/lighthouse/directives/arguments/base.rb +18 -0
  33. data/lib/lighthouse/directives/arguments/filters.rb +16 -7
  34. data/lib/lighthouse/directives/definitions.rb +43 -6
  35. data/lib/lighthouse/document_ast.rb +6 -0
  36. data/lib/lighthouse/enum_directive.rb +6 -1
  37. data/lib/lighthouse/feature_directive.rb +13 -1
  38. data/lib/lighthouse/graphql/version.rb +1 -1
  39. data/lib/lighthouse/graphql_ruby_patches.rb +26 -2
  40. data/lib/lighthouse/ide_helper.rb +7 -6
  41. data/lib/lighthouse/scalar_coercion.rb +4 -1
  42. data/lib/lighthouse/tasks/lighthouse.rake +8 -0
  43. data/lib/lighthouse/type_resolution.rb +8 -2
  44. data/sig/lighthouse/graphql.rbs +1 -0
  45. metadata +1 -1
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: eec6f789caae61cc196024238623ebc042783884cf8ebb53b19bb0e3f6d2cf3f
4
- data.tar.gz: 61bdd5cef3df0d2c4ac9701501576c96a9c207d81b5f2f976d22e5fee14df9ba
3
+ metadata.gz: 30f0e741c78c61751024d75f1b7599e5e8e1e3b2bc426a48f7b6a89c86eacf19
4
+ data.tar.gz: 45e1282efbb6115e4cf4931fd51a05b85cc8d096d204aba819d90228766da3a7
5
5
  SHA512:
6
- metadata.gz: 11c76fea28a691e29eea4910674585891907cefbeef72e9efc7519b8f812cd26f39d6895c90a46c91259b53c0dc64e3a0437add651d9eed07e5cd74807f245f2
7
- data.tar.gz: 530507331c8736355448b67e1cf6ac354a0745351038fc9e7f8535df47f30299e2cf4ea203bee15482bc3fbcf3b8f9d0e5d7e72c61f263f0d9759016ae210a10
6
+ metadata.gz: a13e0fad7027bf2201b63f1543b95808fd63bc7f0ff0f71b9361c42e72f808b4e6475ac9f82298257884c28ecb878924d2ba7a0b1aa4c2186c049a626962c416
7
+ data.tar.gz: 5f84257bfde8cf780b224f39615b4c8a0cff520479b97e7e106859084e390db0f9fe5a24fff0e2573609e46129c2b43d210a8fa36c3f972da67c1b7f2b3268cd
data/CHANGELOG.md CHANGED
@@ -6,6 +6,37 @@ 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
+
29
+ ## [0.7.1] - 2026-10-18
30
+
31
+ ### Added
32
+
33
+ - **`lighthouse:install` on graphql-ruby's Relay** (`--relay`, its default) writes `node(id:)`
34
+ and `nodes(ids:)` in the starter `graphql/schema.graphql`, with `interface Node` and a
35
+ `User @node` whose ids are global (`id: ID! @globalId`, `user(id: ID! @globalId(decode: ID) @eq)`).
36
+ Graphql-ruby's `field :node` / `field :nodes` move out of `Types::QueryType`, whose
37
+ `#node` / `#nodes` methods resolve the SDL's fields. This happens only when the schema file
38
+ does not exist yet. An install without Relay writes the starter schema as before.
39
+
9
40
  ## [0.7.0] - 2026-10-18
10
41
 
11
42
  The schema is written by PHP Lighthouse's rules now: one entrypoint that imports
@@ -670,7 +701,9 @@ had been running inside a private monorepo as a path gem before being extracted.
670
701
  - Config-driven extension seams: `Lighthouse.configure`, `resolver_namespaces`,
671
702
  `on_error`, and `DirectiveRegistry.register` for app-defined directives.
672
703
 
673
- [Unreleased]: https://github.com/Vaz-Innovation/lighthouse-graphql/compare/v0.7.0...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
706
+ [0.7.1]: https://github.com/Vaz-Innovation/lighthouse-graphql/compare/v0.7.0...v0.7.1
674
707
  [0.7.0]: https://github.com/Vaz-Innovation/lighthouse-graphql/compare/v0.6.0...v0.7.0
675
708
  [0.6.0]: https://github.com/Vaz-Innovation/lighthouse-graphql/compare/v0.5.0...v0.6.0
676
709
  [0.5.0]: https://github.com/Vaz-Innovation/lighthouse-graphql/compare/v0.4.0...v0.5.0
data/docs/generators.md CHANGED
@@ -32,7 +32,7 @@ And it adds Lighthouse's own:
32
32
  | File | What it is |
33
33
  | --- | --- |
34
34
  | `config/initializers/lighthouse.rb` | Every [configuration](configuration.md) option, commented out |
35
- | `graphql/schema.graphql` | A starter schema, unless the folder holds `.graphql` files already |
35
+ | `graphql/schema.graphql` | A starter schema, unless the file exists. With graphql-ruby's Relay (`--relay`, its default), it declares `Query.node` and `nodes`, `interface Node`, and a `User @node` with global ids, and `Types::QueryType`'s `field :node` / `:nodes` go: its `#node` / `#nodes` resolve the SDL's |
36
36
  | `graphql.config.yml` | IDE configuration, and `.gitignore` entries for the [IDE helper](getting-started.md#ide-support) files |
37
37
  | `app/graphql/subscriptions/base_subscription.rb` | With `--subscriptions` only: graphql-ruby has no subscription base. It includes `Lighthouse::GraphQL::Subscription` |
38
38
  | `config/routes.rb` | `post "/graphql", to: "graphql#execute"`, when missing |
@@ -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
 
@@ -37,7 +60,7 @@ graphql-ruby wrote, and adds Lighthouse's own:
37
60
  | `app/graphql/types/base_*.rb`, `resolvers/base_resolver.rb`, `mutations/base_mutation.rb` | graphql-ruby's base classes. `BaseObject`, `BaseInterface`, `BaseUnion` and `BaseScalar` include `Lighthouse::GraphQL::Type` |
38
61
  | `app/controllers/graphql_controller.rb` | graphql-ruby's controller, replaced by one including `Lighthouse::GraphQL::Controller` |
39
62
  | `config/initializers/lighthouse.rb` | Every [configuration](configuration.md) option, commented out at its default |
40
- | `graphql/schema.graphql` | The schema's entrypoint: a starter schema (`user` via `@find`, `users` via `@paginate`) that assumes a `User` model. Skipped when the file exists |
63
+ | `graphql/schema.graphql` | The schema's entrypoint: a starter schema (`user` via `@find`, `users` via `@paginate`) that assumes a `User` model. With graphql-ruby's Relay, also `node(id:)` and `nodes(ids:)` (see [relay.md](relay.md#relay-through-graphql-ruby)). Skipped when the file exists |
41
64
  | `graphql.config.yml` | IDE configuration — see [IDE support](#ide-support) |
42
65
 
43
66
  `--schema=ApiSchema`, `--schema-path=app/schema/schema.graphql`, `--subscriptions`,
@@ -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.
data/docs/relay.md CHANGED
@@ -160,9 +160,58 @@ directives then work on them. The schema has one kind of global id and one `Node
160
160
  `ID` gives its id, and `ARRAY` / `TYPE` its class name (`["Tag", 1]`, `"Tag"`).
161
161
  - `node:` is the SDL's `Node` interface: `interface Node`, which `@node` adds, and
162
162
  `implements Node` refer to `Types::NodeType`. A `@node` type implements it.
163
- - `Query.node` and `nodes` are graphql-ruby's code-first fields of
164
- `Types::QueryType`, which find objects with `object_from_id`. The `node` field
165
- `@node` would add to `Query` gives way to them.
163
+ - `Query.node` and `nodes` find objects with `object_from_id`, through the
164
+ `#node` and `#nodes` methods of `Types::QueryType`. `lighthouse:install`
165
+ declares both fields in the starter `graphql/schema.graphql`, and removes the
166
+ `field :node` / `field :nodes` that graphql-ruby wrote in `Types::QueryType`,
167
+ so the SDL is where they are declared. An SDL field without a resolving
168
+ directive resolves with the root type class's method of its name. If the
169
+ fields stay in `Types::QueryType` instead, they are part of the schema too, and
170
+ the `node` field `@node` would add to `Query` gives way to them.
171
+
172
+ The starter schema `lighthouse:install` writes on graphql-ruby's Relay:
173
+
174
+ ```graphql
175
+ type Query {
176
+ "Fetches an object given its ID. Resolved by Types::QueryType#node, with AppSchema.object_from_id."
177
+ node("ID of the object." id: ID!): Node
178
+
179
+ "Fetches a list of objects given a list of IDs. Resolved by Types::QueryType#nodes."
180
+ nodes("IDs of the objects." ids: [ID!]!): [Node]
181
+
182
+ user(id: ID! @globalId(decode: ID) @eq): User @find
183
+ users: [User!]! @paginate(defaultCount: 10)
184
+ }
185
+
186
+ interface Node {
187
+ "ID of the object."
188
+ id: ID!
189
+ }
190
+
191
+ type User @node {
192
+ id: ID! @globalId
193
+ name: String
194
+ email: String
195
+ }
196
+ ```
197
+
198
+ ```ruby
199
+ module Types
200
+ class QueryType < Types::BaseObject
201
+ # Query.node and nodes are declared in graphql/schema.graphql; these methods resolve them.
202
+ def node(id:)
203
+ context.schema.object_from_id(id, context)
204
+ end
205
+
206
+ def nodes(ids:)
207
+ ids.map { |id| context.schema.object_from_id(id, context) }
208
+ end
209
+ end
210
+ end
211
+ ```
212
+
213
+ `lighthouse:install` writes this only when the app has no schema file yet, and
214
+ only on the `node` / `nodes` fields as graphql-ruby writes them.
166
215
 
167
216
  ```graphql
168
217
  type Tag @node {
@@ -26,6 +26,10 @@ module Lighthouse::Generators::GraphqlRubyInstall
26
26
  # The example field graphql-ruby's install puts in each root type.
27
27
  TEST_FIELD = /\n+[ \t]*# TODO: remove me\n[ \t]*field :test_field,.*?\n[ \t]*def test_field\n.*?\n[ \t]*end\n/m
28
28
 
29
+ # The `node` and `nodes` fields graphql-ruby's install (--relay, its default)
30
+ # puts in Types::QueryType, without the methods that resolve them.
31
+ RELAY_FIELDS = /^[ \t]*field :nodes?, \[?Types::NodeType\b.*? do\n(?:[ \t]*argument .*\n)*[ \t]*end\n\n?/
32
+
29
33
  # The `resolve_type` stub graphql-ruby's install puts in the schema class.
30
34
  RESOLVE_TYPE_STUB = /
31
35
  \n+[ \t]*\#\ Union\ and\ Interface\ Resolution\n
@@ -98,6 +102,16 @@ module Lighthouse::Generators::GraphqlRubyInstall
98
102
  options[:subscriptions] || exist?(File.join(directory, 'subscriptions', 'base_subscription.rb'))
99
103
  end
100
104
 
105
+ # Did graphql-ruby's install write Relay's side (--relay, its default):
106
+ # Types::NodeType, and Types::QueryType's node and nodes, as it writes them?
107
+ def relay?
108
+ query_type = types_path('query_type.rb')
109
+ return false unless exist?(types_path('node_type.rb')) && exist?(query_type)
110
+
111
+ source = read(query_type)
112
+ source.scan(RELAY_FIELDS).size == 2 && source.include?('def node(id:)') && source.include?('def nodes(ids:)')
113
+ end
114
+
101
115
  def graphql_ruby_controller?(source)
102
116
  source.include?('def prepare_variables(variables_param)') && source.include?('def handle_error_in_development(e)') &&
103
117
  source.include?("#{schema_name}.execute(query, variables: variables, context: context, operation_name: operation_name)")
@@ -21,6 +21,9 @@ require_relative 'graphql_ruby_install'
21
21
  # graphql-ruby's and stays, but the `resolve_type` stub (Lighthouse resolves
22
22
  # types) and the root types it is built on;
23
23
  # - the example `test_field` goes from the root types;
24
+ # - with Relay, the starter SDL declares Query.node and nodes (and a User
25
+ # @node with global ids), so their `field`s go from Types::QueryType, whose
26
+ # #node / #nodes methods resolve the SDL's fields;
24
27
  # - graphql-ruby's base object, interface, union and scalar include
25
28
  # Lighthouse::GraphQL::Type, so every type class (Types::QueryType,
26
29
  # Types::NodeType, what `graphql:object` writes) is Lighthouse's;
@@ -76,6 +79,7 @@ class Lighthouse::Generators::InstallGenerator < Rails::Generators::Base
76
79
  return
77
80
  end
78
81
 
82
+ @relay_starter = relay?
79
83
  template 'schema.graphql.tt', sdl_schema_path
80
84
  end
81
85
 
@@ -101,12 +105,15 @@ class Lighthouse::Generators::InstallGenerator < Rails::Generators::Base
101
105
  add_dataloader if source.include?('use GraphQL::Batch') && source.exclude?('use GraphQL::Dataloader')
102
106
  end
103
107
 
104
- # The example field goes; the root types' own fields stay.
108
+ # The example field goes; the root types' own fields stay. With Relay, the
109
+ # starter SDL declares Query.node and nodes, so their `field`s go too, and
110
+ # the methods graphql-ruby wrote resolve the SDL's fields.
105
111
  def adapt_root_types
106
112
  %w[query_type mutation_type subscription_type].each do |name|
107
113
  path = types_path("#{name}.rb")
108
114
  gsub_file path, TEST_FIELD, "\n" if exist?(path) && read(path).match?(TEST_FIELD)
109
115
  end
116
+ move_relay_fields_to_sdl if @relay_starter
110
117
  end
111
118
 
112
119
  # Every type class is Lighthouse's: graphql-ruby's base object, interface,
@@ -223,6 +230,13 @@ class Lighthouse::Generators::InstallGenerator < Rails::Generators::Base
223
230
  sdl_schema_path == 'graphql/schema.graphql'
224
231
  end
225
232
 
233
+ def move_relay_fields_to_sdl
234
+ path = types_path('query_type.rb')
235
+ gsub_file path, RELAY_FIELDS, ''
236
+ gsub_file path, /^([ \t]*)def node\(id:\)\n/,
237
+ "\\1# Query.node and nodes are declared in #{sdl_schema_path}; these methods resolve them.\n\\1def node(id:)\n"
238
+ end
239
+
226
240
  def ide_helper_files
227
241
  [Lighthouse::IdeHelper::DIRECTIVES_FILE, Lighthouse::IdeHelper::PROGRAMMATIC_TYPES_FILE]
228
242
  end
@@ -1,15 +1,44 @@
1
1
  # Starter schema generated by `rails generate lighthouse:install`. It assumes a
2
2
  # User model with `name` and `email` columns — replace it with your own types.
3
+ # This file is the schema's entrypoint: split the schema into files it imports
4
+ # (#import user.graphql), which add their fields with `extend type Query`.
3
5
  # Directives reference: https://github.com/Vaz-Innovation/lighthouse-graphql/blob/main/docs/directives.md
4
6
 
5
7
  "Indicates what fields are available at the top level of a query operation."
6
8
  type Query {
9
+ <% if relay? -%>
10
+ "Fetches an object given its ID. Resolved by Types::QueryType#node, with <%= schema_name %>.object_from_id."
11
+ node("ID of the object." id: ID!): Node
12
+
13
+ "Fetches a list of objects given a list of IDs. Resolved by Types::QueryType#nodes."
14
+ nodes("IDs of the objects." ids: [ID!]!): [Node]
15
+
16
+ "Find a single user by its global id."
17
+ user(id: ID! @globalId(decode: ID) @eq): User @find
18
+ <% else -%>
7
19
  "Find a single user by id."
8
20
  user(id: ID! @eq): User @find
21
+ <% end -%>
9
22
 
10
23
  "List users, a page at a time (10 by default; pass first: and page:)."
11
24
  users: [User!]! @paginate(defaultCount: 10)
12
25
  }
26
+ <% if relay? -%>
27
+
28
+ "An object with an ID: graphql-ruby's Types::NodeType."
29
+ interface Node {
30
+ "ID of the object."
31
+ id: ID!
32
+ }
33
+
34
+ "Account of a person who uses this application. @node makes it a Node, which Query.node finds."
35
+ type User @node {
36
+ "Its global id, from <%= schema_name %>.id_from_object (Rails' GlobalID)."
37
+ id: ID! @globalId
38
+ name: String
39
+ email: String
40
+ }
41
+ <% else -%>
13
42
 
14
43
  "Account of a person who uses this application."
15
44
  type User {
@@ -17,3 +46,4 @@ type User {
17
46
  name: String
18
47
  email: String
19
48
  }
49
+ <% end -%>
@@ -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