lighthouse-graphql 0.7.2 → 0.8.0

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 +126 -1
  3. data/docs/authorization.md +33 -1
  4. data/docs/configuration.md +38 -0
  5. data/docs/directives.md +51 -4
  6. data/docs/filtering-and-ordering.md +52 -0
  7. data/docs/getting-started.md +63 -10
  8. data/docs/performance.md +9 -0
  9. data/docs/relay.md +6 -2
  10. data/docs/uploads.md +28 -2
  11. data/lib/lighthouse/ast_builder.rb +14 -5
  12. data/lib/lighthouse/config.rb +18 -2
  13. data/lib/lighthouse/controller.rb +6 -67
  14. data/lib/lighthouse/directive_resolvers/argument_transforms_resolver.rb +7 -1
  15. data/lib/lighthouse/directive_resolvers/association_resolvers.rb +5 -7
  16. data/lib/lighthouse/directive_resolvers/attachment_resolver.rb +139 -0
  17. data/lib/lighthouse/directive_resolvers/base.rb +26 -22
  18. data/lib/lighthouse/directive_resolvers/can_resolvers.rb +29 -5
  19. data/lib/lighthouse/directive_resolvers/model_mutation_resolver.rb +1 -8
  20. data/lib/lighthouse/directives/definitions.rb +2 -2
  21. data/lib/lighthouse/directives/registry.rb +1 -1
  22. data/lib/lighthouse/directives/soft_deletes_directive.rb +23 -6
  23. data/lib/lighthouse/document_ast.rb +6 -0
  24. data/lib/lighthouse/field_resolver_stack.rb +32 -0
  25. data/lib/lighthouse/global_id.rb +16 -5
  26. data/lib/lighthouse/graphql/version.rb +1 -1
  27. data/lib/lighthouse/operations.rb +111 -0
  28. data/lib/lighthouse/pagination.rb +21 -1
  29. data/lib/lighthouse/persisted_queries/manifest.rb +40 -0
  30. data/lib/lighthouse/persisted_queries.rb +9 -27
  31. data/lib/lighthouse/railtie.rb +8 -1
  32. data/lib/lighthouse/rb_lighthouse.rb +6 -0
  33. data/lib/lighthouse/relation_batch.rb +1 -1
  34. data/lib/lighthouse/schema_generator.rb +2 -0
  35. data/lib/lighthouse/schema_printer.rb +100 -0
  36. data/lib/lighthouse/schema_report.rb +161 -0
  37. data/lib/lighthouse/server_directives.rb +63 -0
  38. data/lib/lighthouse/tasks/lighthouse.rake +25 -6
  39. data/lib/lighthouse/upload.rb +2 -1
  40. data/lib/lighthouse/upload_store.rb +53 -2
  41. data/sig/lighthouse/controller.rbs +19 -8
  42. data/sig/lighthouse/directives.rbs +27 -0
  43. data/sig/lighthouse/graphql.rbs +3 -0
  44. data/sig/lighthouse.rbs +11 -2
  45. metadata +7 -1
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 30f0e741c78c61751024d75f1b7599e5e8e1e3b2bc426a48f7b6a89c86eacf19
4
- data.tar.gz: 45e1282efbb6115e4cf4931fd51a05b85cc8d096d204aba819d90228766da3a7
3
+ metadata.gz: f307869fd0902be910da0c9edad56620a3339962ccb77e388b7b11aad1565fde
4
+ data.tar.gz: 3e9164c49b69dcf6626b6985266fd33a65c90a76cf065e44efe7cee5bc250b0f
5
5
  SHA512:
6
- metadata.gz: a13e0fad7027bf2201b63f1543b95808fd63bc7f0ff0f71b9361c42e72f808b4e6475ac9f82298257884c28ecb878924d2ba7a0b1aa4c2186c049a626962c416
7
- data.tar.gz: 5f84257bfde8cf780b224f39615b4c8a0cff520479b97e7e106859084e390db0f9fe5a24fff0e2573609e46129c2b43d210a8fa36c3f972da67c1b7f2b3268cd
6
+ metadata.gz: ac2430336cfdc489d2d032d038ad3227d45cfd92101f66c4eff3c5a83b1325058d1e65fd16430fecf2a0b358849427e9be31a1b3ba2b309c787873cf20bf41bc
7
+ data.tar.gz: 8c9c10c5650b02845daa40cc74ad76909e8ea7622221d19d204a2b77fd3cec08b9686339c8b2606e067a06f4ba56a4d13111b42b155e0d8d0e5c5ed4831d6558
data/CHANGELOG.md CHANGED
@@ -6,6 +6,124 @@ project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
6
6
 
7
7
  ## [Unreleased]
8
8
 
9
+ ## [0.8.0] - 2026-10-29
10
+
11
+ ### Added
12
+
13
+ - **`config.schema_log` reports the schema on boot and on every reload in development**: a
14
+ pretty-printed `✓` with the build time, the number of types and root fields, what the reload
15
+ added and removed (`+ User.nickname − Post.legacyTitle`) and the files written, or a `✗`
16
+ with the error the next request would raise, plus the persisted operations the schema no
17
+ longer accepts. On by default in a development server (not rake tasks or the console),
18
+ through the Rails logger, and on the terminal from boot.
19
+ - **`@attachment` answers the URL of an ActiveStorage attachment**, or the URLs of a
20
+ `has_many_attached`: the read side of `@upload`. Every parent's attachments and blobs load
21
+ at once (two queries for any number of parents), the name defaults to the field's without
22
+ `Url`/`Urls` (`avatarUrl` reads `avatar`), and `url:` picks Rails' `REDIRECT` (default),
23
+ `PROXY`, or the service's `DIRECT` URL signed for `expiresIn`; `variant:` names a variant.
24
+ - **`@canModel` on an argument or input field: who may use it.** It checks its ability against
25
+ the model only when the client gives that argument a value, at any depth (in each input of
26
+ a list too), with the field's `@can*` directives and their `action:`.
27
+ `@softDeletes(ability: "view_trashed")` puts it on the `trashed` argument it adds, so
28
+ listing trashed records can be for admins only.
29
+ - **`lighthouse_execute` runs an operation from any controller action (#3)**, with the context the
30
+ GraphQL endpoint gives it (`graphql_context`, and the IP and controller `@throttle` counts
31
+ with), to render a page with its data loaded. It comes from the new
32
+ `Lighthouse::GraphQL::Operations` concern, which any controller can include (with
33
+ `lighthouse_schema`), and which `Lighthouse::GraphQL::Controller` includes. It returns the
34
+ result, or `nil` when a `@throttle` answered the request with a 429.
35
+ - `config.persisted_queries_manifest` takes a Hash of operations, or a callable answering a
36
+ Hash or a path (called per persisted query), besides a JSON file: a frontend build can keep
37
+ its trusted documents where it writes them. A Hash is checked once, until its content changes.
38
+ - **`config.schema_output` keeps the client schema in a file, in development**, for a codegen
39
+ to read, as NestJS's `autoSchemaFile`: rewritten on boot and on every reload, only when it
40
+ changed (atomically, so a watcher never reads half of it). A path (`.json` for the
41
+ introspection result), or `{ path:, schema: }`. `bin/rails lighthouse:schema_output:verify`
42
+ fails in CI when the committed file is out of date.
43
+ - `lighthouse:print_schema` takes PHP Lighthouse's options: `FORMAT=json` (the introspection
44
+ result), `FORMAT=federation` (a subgraph's SDL), and `WRITE=1` / `WRITE=path` to write a
45
+ file (schema_output's, else `lighthouse-schema.graphql`). graphql-ruby already prints in
46
+ alphabetical order, so there is no `--sort`. With no `SCHEMA=`, it and the other tasks
47
+ (`validate_schema`, `persisted_queries:verify`) take `<App>Schema`, the name graphql-ruby's
48
+ install gives, before trying `AppSchema`.
49
+
50
+ ### Changed
51
+
52
+ - **Clients no longer see Lighthouse's directives.** Introspection listed every directive
53
+ Lighthouse injects to build the schema (`@all`, `@canFind`, `@inject`, `@hash`, ... 96 in
54
+ the example app), with the types only they use (`CanAction`, `FeatureState`), and
55
+ `to_definition` / `lighthouse:print_schema` printed their definitions and every use
56
+ (`author: User! @belongsTo`). As in PHP Lighthouse, whose schema holds only the standard
57
+ directives and those the SDL declares, they are now taken out of the built schema: a client
58
+ sees `@skip`, `@include`, `@deprecated`, `@oneOf`, `@specifiedBy` and the SDL's own, and an
59
+ operation using `@all` is invalid. Lighthouse reads its directives from the SDL, so nothing
60
+ else changes.
61
+
62
+ ### Fixed
63
+
64
+ - **`@upload` purges what it stored when the field fails.** It stores a file before the
65
+ field resolves, and a model's validations run after: a `@create` the model refused left
66
+ its blobs in the bucket (#1). The blobs `@upload` stored for a field that raises, returns
67
+ an error or adds one to the context are now purged before the response (one the storage
68
+ service fails to delete is left to `purge_later`). The uploads guide now
69
+ recommends passing the file to the attachment attribute, which ActiveStorage uploads
70
+ only after commit.
71
+ - **Paginated queries end their order with the primary key.** Pages are cut by position, so
72
+ rows the field's order tied (`@orderBy(column: "created_at")`) could come back in another
73
+ order on the next page's query, and show on two pages or none; the same in the per-parent
74
+ row numbers of a batched relation. `@paginate` (every `type:`) and the paginated relation
75
+ directives now append the primary key unless the order names it already. PHP Lighthouse
76
+ leaves the order as it is.
77
+ - **`@globalId(decode:)` no longer loads the record to read its id (#2).** On a schema with
78
+ graphql-ruby's `object_from_id` (Rails' GlobalID, as its install writes it), decoding went
79
+ through `object_from_id`: a SELECT before `@find`'s own, under the model's default scope,
80
+ so a soft-deleted record's id did not decode for `@restore` / `@forceDelete` with an
81
+ `object_from_id` that kept the scope. A Rails GlobalID now decodes without the database,
82
+ as PHP Lighthouse's `decodeID` does; only an id of another format goes through
83
+ `object_from_id`.
84
+ - A directive the SDL uses that is neither built in, Lighthouse's nor declared fails the build
85
+ with ``No directive found for `@can` on Query.a.``, as PHP Lighthouse names it. On a root type
86
+ it failed with a `NoMethodError` from inside graphql-ruby.
87
+
88
+ - **An optional `Upload` takes an explicit `null`.** The scalar refused it ("Could not get
89
+ uploaded file ... Instead got: nil"), so a client had to leave the argument out. `null`
90
+ now reaches the resolver as `nil`, and `@upload` stores nothing for it.
91
+ - **`@canFind` fails when nothing is at its `find:` path, instead of passing unchecked.** A
92
+ misspelt path (`find: "inputt.id"`), or an optional argument the client left out, found
93
+ no ids, so no model was checked and the field resolved. It now fails with `Got no key to
94
+ find a model at the expected input path: …`, as PHP Lighthouse does (through `action:`,
95
+ like the other failures). A `*` over an empty list still checks no model.
96
+
97
+ ## [0.7.3] - 2026-10-29
98
+
99
+ ### Changed
100
+
101
+ - **Filters on input fields apply without `@nest`, as in PHP Lighthouse.** The filter
102
+ directives (`@eq`, `@where`, `@like`, ...) on an input object's fields apply whenever the
103
+ client sends it: at any depth, for every input of a list (together), and through `@spread`,
104
+ as PHP Lighthouse's `applyArgBuilderDirectives` goes through nested inputs. They used to
105
+ apply only under an argument marked `@nest`, which is still accepted and changes nothing.
106
+ `posts(filter: PostFilter): [Post!]! @all` filters by the `@eq` inside `PostFilter`.
107
+
108
+ ### Fixed
109
+
110
+ - **A definition of a built-in directive in the SDL no longer disables it.** graphql-ruby
111
+ replaced its `@oneOf`, `@skip`, `@include`, `@deprecated` and `@specifiedBy` with a plain
112
+ directive of the same name when the SDL declared one (`directive @oneOf on INPUT_OBJECT`),
113
+ so a `@oneOf` input accepted any number of fields while introspection still reported
114
+ `isOneOf: true`, and `@skip` skipped nothing. Lighthouse now drops those definitions and
115
+ keeps graphql-ruby's directives.
116
+ - A relation field (`@hasMany`, ...) filtered only through an input object's fields took the
117
+ batched load and ignored the filters, and `@delete`, `@forceDelete` and `@restore` refused
118
+ such an argument as no filter ("Would modify all models"). Both now see nested filters.
119
+
120
+ ### Added
121
+
122
+ - `@oneOf` input objects are documented and specced
123
+ ([Filtering & Ordering](docs/filtering-and-ordering.md#one-filter-of-several-oneof)):
124
+ `user(by: UserBy!): User @find` finds by whichever one field the client gives, and
125
+ graphql-ruby rejects a query giving none or more than one.
126
+
9
127
  ## [0.7.2] - 2026-10-29
10
128
 
11
129
  ### Added
@@ -26,6 +144,11 @@ project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
26
144
  - The `_` placeholder exists only for the IDE: a `scalar _` in your SDL is dropped once the
27
145
  schema builds, so the executable schema (and its introspection) has no `_` type.
28
146
 
147
+ ### Fixed
148
+
149
+ - Builds on graphql-ruby 2.6.14, whose changed internals made the root types
150
+ (`Types::QueryType`, ...) lose the app's code-first base.
151
+
29
152
  ## [0.7.1] - 2026-10-18
30
153
 
31
154
  ### Added
@@ -701,7 +824,9 @@ had been running inside a private monorepo as a path gem before being extracted.
701
824
  - Config-driven extension seams: `Lighthouse.configure`, `resolver_namespaces`,
702
825
  `on_error`, and `DirectiveRegistry.register` for app-defined directives.
703
826
 
704
- [Unreleased]: https://github.com/Vaz-Innovation/lighthouse-graphql/compare/v0.7.2...HEAD
827
+ [Unreleased]: https://github.com/Vaz-Innovation/lighthouse-graphql/compare/v0.8.0...HEAD
828
+ [0.8.0]: https://github.com/Vaz-Innovation/lighthouse-graphql/compare/v0.7.3...v0.8.0
829
+ [0.7.3]: https://github.com/Vaz-Innovation/lighthouse-graphql/compare/v0.7.2...v0.7.3
705
830
  [0.7.2]: https://github.com/Vaz-Innovation/lighthouse-graphql/compare/v0.7.1...v0.7.2
706
831
  [0.7.1]: https://github.com/Vaz-Innovation/lighthouse-graphql/compare/v0.7.0...v0.7.1
707
832
  [0.7.0]: https://github.com/Vaz-Innovation/lighthouse-graphql/compare/v0.6.0...v0.7.0
@@ -107,7 +107,10 @@ Plus, per directive:
107
107
  - `@canFind(find: String!, model: String, findOrFail: Boolean = true, scopes: [String!])`.
108
108
  `find` is the argument holding the primary key or keys, and may be a dot path
109
109
  (`"input.id"`). A key that matches no record fails with
110
- `Couldn't find Post with 'id'=…`, unless `findOrFail: false`. `scopes` are model
110
+ `Couldn't find Post with 'id'=…`, unless `findOrFail: false`. Nothing at the path (a
111
+ misspelt one, or an optional argument the client left out) fails with
112
+ `Got no key to find a model at the expected input path: …`, as in PHP Lighthouse;
113
+ a `*` over an empty list (`"inputs.*.id"`) checks no model. `scopes` are model
111
114
  scopes applied to the lookup.
112
115
  - `@canModel(model: String)`.
113
116
  - `@canQuery(model: String, scopes: [String!])`. `scopes` narrow the records
@@ -131,6 +134,35 @@ post(id: ID!): Post @canFind(ability: "show", find: "id", action: EXCEPTION_NOT_
131
134
  `action` applies to the directive's own checks only. Errors from the resolver
132
135
  itself are untouched.
133
136
 
137
+ ### Who may use an argument
138
+
139
+ Some arguments are for some users only: `trashed` for admins, a filter on drafts
140
+ for editors. `@canModel` on an argument, or on an input field at any depth, checks
141
+ its ability against the model only when the client gives that argument a value, and
142
+ denies the whole field otherwise, as `@canModel` on the field does (`action:` too):
143
+
144
+ ```graphql
145
+ type Query {
146
+ posts(filter: PostFilter): [Post!]! @all
147
+ tasks(trashed: Trashed @trashed @canModel(ability: "view_trashed")): [Task!]! @all
148
+ }
149
+
150
+ input PostFilter {
151
+ title: String @like
152
+ status: PostStatus @eq @canModel(ability: "filter_by_status", model: "Post")
153
+ }
154
+ ```
155
+
156
+ ```ruby
157
+ class TaskPolicy < ApplicationPolicy
158
+ def view_trashed? = user&.admin?
159
+ end
160
+ ```
161
+
162
+ It runs with the field's `@can*` directives, before the field resolves. The model is
163
+ the directive's `model:`, else the field's, as for `@canModel` on a field.
164
+ `@softDeletes(ability:)` writes it on the `trashed` argument for you.
165
+
134
166
  ## Ordering
135
167
 
136
168
  The order you write directives in does not matter. They run as:
@@ -38,6 +38,44 @@ content is unchanged is left alone. `nil` (the default) turns it on in
38
38
  development when the app has a `graphql.config.yml`, which `lighthouse:install`
39
39
  writes. Set `true` or `false` to decide yourself.
40
40
 
41
+ ### `schema_log`
42
+
43
+ Log what development learns of the schema on boot and on every reload: it built (in
44
+ how long, how big, what the reload added and removed, the files it wrote), or why it
45
+ did not, and the persisted operations it no longer accepts:
46
+
47
+ ```text
48
+ [Lighthouse] ✓ AppSchema built in 61 ms: 47 types, 16 queries, 9 mutations, 3 subscriptions
49
+ [Lighthouse] + User.nickname − Post.legacyTitle
50
+ [Lighthouse] wrote schema.graphql
51
+
52
+ [Lighthouse] ✗ The schema does not build: Lighthouse::DefinitionError
53
+ [Lighthouse] No directive found for `@can` on User.nickname.
54
+ [Lighthouse] The next GraphQL request raises it: save a fix to reload.
55
+ ```
56
+
57
+ The schema is checked as `bin/rails lighthouse:validate_schema` checks it (the
58
+ `ValidateSchema` event, then every type), through the Rails logger, in colour when
59
+ `config.colorize_logging` is on. `nil` (the default) logs in a development server,
60
+ not in rake tasks or the console; `true` or `false` decide.
61
+
62
+ ### `schema_output`
63
+
64
+ A file development keeps the schema clients see in, for a codegen to read, as
65
+ NestJS's `autoSchemaFile`: rewritten on boot and on every reload, and only when it
66
+ changed, so a watcher runs only then ([`schema_log`](#schema-log) says when it did). A path under the app's root, whose extension
67
+ picks the format (`.json` for the introspection result, else SDL), or a Hash naming
68
+ the schema class too (`<App>Schema`, graphql-ruby's install's name, by default):
69
+
70
+ ```ruby
71
+ config.schema_output = 'schema.graphql'
72
+ config.schema_output = { path: 'app/javascript/graphql/schema.json', schema: 'Admin::Schema' }
73
+ ```
74
+
75
+ Commit the file and check it in CI with `bin/rails lighthouse:schema_output:verify`,
76
+ which fails when it is out of date; `bin/rails lighthouse:print_schema WRITE=1`
77
+ rewrites it. See [printing the schema](getting-started.md#the-schema-clients-see).
78
+
41
79
  ### `namespaces`
42
80
 
43
81
  Where each kind of class a schema names is looked up, by kind — they have
data/docs/directives.md CHANGED
@@ -89,6 +89,11 @@ type Query {
89
89
  - **The total** is only counted when the client selects `paginatorInfo` or
90
90
  `pageInfo`.
91
91
  - **Cursors** are base64 of the item's position.
92
+ - **The order** ends with the primary key: a page is cut by position, so rows the
93
+ field's order ties (`@orderBy(column: "created_at")` on posts created in the same
94
+ second), or a query with no order, would otherwise come back in another order on
95
+ the next page, and a row would show on two pages or none. An order that names
96
+ the key already, or a grouped query, is left as it is. PHP Lighthouse does not add it.
92
97
 
93
98
  ### `@count`
94
99
 
@@ -247,6 +252,35 @@ keywords (`def summary(words:)`), otherwise positionally, in the order the SDL
247
252
  declares them, as PHP Lighthouse passes them (`def summary(words)`). The SDL's
248
253
  defaults apply, and a method taking no parameters is called without them.
249
254
 
255
+ ### `@attachment`
256
+
257
+ The URL of an ActiveStorage attachment of the parent, or the URLs of a
258
+ `has_many_attached`: the read side of [`@upload`](uploads.md). Lighthouse's own, as
259
+ Laravel has no ActiveStorage.
260
+
261
+ ```graphql
262
+ type User {
263
+ avatarUrl: String @attachment # has_one_attached :avatar
264
+ avatarThumbUrl: String @attachment(name: "avatar", variant: "thumb")
265
+ photoUrls: [String!]! @attachment(url: PROXY) # has_many_attached :photos
266
+ }
267
+ ```
268
+
269
+ - **`name`** defaults to the field's name without its `Url` / `Urls` suffix:
270
+ `avatarUrl` reads `avatar`, `photoUrls` reads `photos`. A missing attachment is
271
+ `null`, a model without one of that name an error.
272
+ - **Every parent's attachments and blobs load at once**, two queries for any
273
+ number of users (`avatar_attachment: :blob`, what `User.with_attached_avatar`
274
+ loads), through the Dataloader when the schema uses it.
275
+ - **`url`**: `REDIRECT` (default) is Rails' redirect to the storage service,
276
+ `PROXY` streams the file through the app, and `DIRECT` is the service's own URL,
277
+ signed for `expiresIn` seconds on a private one (`ActiveStorage.service_urls_expire_in`
278
+ by default). The URL is absolute with the request's host, else a path.
279
+ - **`variant`** names a variant of the attachment
280
+ (`has_one_attached :avatar { |attachable| attachable.variant :thumb, resize_to_limit: [100, 100] }`).
281
+ A file that is not an image has none: `null`. A `REDIRECT` or `PROXY` variant is
282
+ processed when its URL is first followed; `DIRECT` processes it while resolving.
283
+
250
284
  ## Relay
251
285
 
252
286
  ### `@globalId` and `@node`
@@ -545,7 +579,7 @@ type Query {
545
579
  createdAt: DateRange @whereBetween(key: "created_at")
546
580
  tagged: [String!] @whereJsonContains(key: "tags")
547
581
  trending: Boolean @scope
548
- filter: PostFilter @nest
582
+ filter: PostFilter
549
583
  limit: Int @limit
550
584
  ): [Post!]! @all
551
585
  }
@@ -554,11 +588,14 @@ input DateRange { from: DateTime! to: DateTime! }
554
588
  input PostFilter { title: String @like, authorId: ID @eq(key: "author_id") }
555
589
  ```
556
590
 
591
+ The filters on an input object's fields (`filter: PostFilter` above) apply when
592
+ the client sends it, at any depth and for each input of a list, as PHP
593
+ Lighthouse applies them. Those of a list's inputs all apply together.
594
+
557
595
  ### `@nest`
558
596
 
559
- On an argument whose type is an input object, applies the filters of the input's
560
- fields (at any depth, for those that carry `@nest` too), as if they were the
561
- field's own arguments.
597
+ Accepted as PHP Lighthouse's SDL writes it, on an argument or input field of an
598
+ input object type. Filters on nested input fields apply without it.
562
599
 
563
600
  ### `@limit`
564
601
 
@@ -764,6 +801,16 @@ enum Trashed {
764
801
  }
765
802
  ```
766
803
 
804
+ Anyone may pass `trashed` unless you say who: `@softDeletes(ability: "view_trashed")`
805
+ puts [`@canModel`](authorization.md#who-may-use-an-argument) on the argument it adds,
806
+ so a client that passes `trashed` (any value) needs the ability on the model's policy.
807
+ Leaving `trashed` out lists the records as usual. PHP Lighthouse has no `ability:`.
808
+
809
+ ```graphql
810
+ tasks: [Task!]! @all @softDeletes(ability: "view_trashed")
811
+ # tasks(trashed: Trashed @trashed @canModel(ability: "view_trashed")): [Task!]! @all
812
+ ```
813
+
767
814
  ### `@trashed`
768
815
 
769
816
  The argument builder `@softDeletes` adds; use it by hand to name the argument
@@ -54,6 +54,58 @@ type Query {
54
54
  }
55
55
  ```
56
56
 
57
+ ### Filters inside input objects
58
+
59
+ Filter directives also go on the fields of an input object. Its fields' filters
60
+ apply when the client sends it, at any depth, as in PHP Lighthouse:
61
+
62
+ ```graphql
63
+ input PostFilter {
64
+ title: String @like
65
+ author: AuthorFilter
66
+ }
67
+
68
+ input AuthorFilter { id: ID @eq(key: "author_id") }
69
+
70
+ type Query {
71
+ posts(filter: PostFilter): [Post!]! @all
72
+ }
73
+ ```
74
+
75
+ `posts(filter: { author: { id: 1 } })` keeps the posts of author 1. In a list of
76
+ inputs (`filters: [PostFilter!]`), every input's filters apply, together. An
77
+ argument with `@spread` filters the same way.
78
+
79
+ ### One filter of several: `@oneOf`
80
+
81
+ An input object marked [`@oneOf`](https://spec.graphql.org/draft/#sec-OneOf-Input-Objects)
82
+ takes exactly one of its fields: to find a user by id **or** by email, but not
83
+ both. Its fields' filters apply to the query:
84
+
85
+ ```graphql
86
+ input UserBy @oneOf {
87
+ id: ID @eq
88
+ email: String @eq
89
+ }
90
+
91
+ type Query {
92
+ user(by: UserBy!): User @find
93
+ }
94
+ ```
95
+
96
+ ```graphql
97
+ { user(by: { email: "ada@example.com" }) { id } }
98
+ ```
99
+
100
+ graphql-ruby validates it: a query giving two fields, none, or a `null` is rejected
101
+ before anything resolves, and introspection reports the type's `isOneOf`. Every
102
+ field of a `@oneOf` input is nullable and has no default value; the schema fails to
103
+ build otherwise.
104
+
105
+ `@oneOf` is built in, so the SDL needn't declare it. A `directive @oneOf on
106
+ INPUT_OBJECT` copied from elsewhere is ignored, like a definition of `@skip`,
107
+ `@include`, `@deprecated` or `@specifiedBy`: graphql-ruby's own directive stays.
108
+
57
109
  ## Ordering
58
110
 
59
111
  `@orderBy` works as in PHP Lighthouse. On an argument, the client picks the
@@ -267,13 +267,48 @@ Route to it (`post '/graphql', to: 'graphql#execute'`, plus a `get` for
267
267
  - renders the JSON; in development an error renders as JSON with its backtrace.
268
268
 
269
269
  The hooks `graphql_context`, `graphql_schema` and `graphql_variables(param)` are
270
- private methods you can override. A controller with an action of its own wraps it
271
- in `lighthouse_request { ... }` to keep the request events:
270
+ private methods you can override.
271
+
272
+ ### Running an operation from another action
273
+
274
+ To render a page with its data already loaded, run the operation from the action
275
+ with `lighthouse_execute`, from `Lighthouse::GraphQL::Operations` (which
276
+ `Lighthouse::GraphQL::Controller` includes). It runs the operation as the endpoint
277
+ does, with the endpoint's context: `graphql_context`, and the client's IP and the
278
+ controller `@throttle` counts with. It returns the result, or `nil` when a
279
+ `@throttle` answered the request with a 429:
280
+
281
+ ```ruby
282
+ class PagesController < ApplicationController
283
+ include Lighthouse::GraphQL::Operations
284
+
285
+ lighthouse_schema AppSchema
286
+
287
+ def search
288
+ @results = lighthouse_execute('query Search($term: String!) { searchPosts(term: $term) { title } }',
289
+ variables: { term: params[:term] })
290
+ return if performed? # @throttle answered 429
291
+ end
292
+
293
+ private
294
+
295
+ def graphql_context = { current_user: current_user }
296
+ end
297
+ ```
298
+
299
+ `extensions:` runs a persisted query by its hash, and `context:` adds to the
300
+ context. The operation events (`StartOperationOrOperations`, `StartExecution`, ...)
301
+ fire as for a client's request. The request events (`StartRequest`, `EndRequest`)
302
+ are the GraphQL endpoint's, one per GraphQL request, as PHP Lighthouse's controller
303
+ dispatches them. `EndRequest` carries the response, which does not exist yet while
304
+ the action is still loading its data, so wrap the whole action in
305
+ `lighthouse_request { ... }` to dispatch them around it, with the page's response:
272
306
 
273
307
  ```ruby
274
308
  def search
275
309
  lighthouse_request do
276
- render json: Lighthouse::GraphQL::PersistedQueries.execute(AppSchema, query: params[:q], context: graphql_context)
310
+ results = lighthouse_execute(SEARCH, variables: { term: params[:term] })
311
+ render inertia: 'Search', props: { results: results } unless performed?
277
312
  end
278
313
  end
279
314
  ```
@@ -348,18 +383,36 @@ VS Code. The files are derived from your schema, so the generator adds them to
348
383
  registering a directive. The IDE reads every `.graphql` file the glob matches, as
349
384
  one schema: it does not follow `#import`.
350
385
 
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:
386
+ > The IDE reads fields as you wrote them: `users: [User!]! @paginate` still looks
387
+ > like a list to it, although clients query `users { data { … } }`. Field
388
+ > rewrites are not something an extra file can express.
389
+
390
+ ### The schema clients see
391
+
392
+ Print it, as PHP Lighthouse's `lighthouse:print-schema` does: every type Lighthouse
393
+ generated, the fields rewritten (`users { data { … } }`), and none of Lighthouse's
394
+ directives, which instruct the server and are not part of the schema clients get
395
+ (nor of introspection). The task writes the SDL to stdout and nothing else:
354
396
 
355
397
  ```shell
356
- bin/rails lighthouse:print_schema # AppSchema
398
+ bin/rails lighthouse:print_schema # <App>Schema, else AppSchema
357
399
  SCHEMA=Admin::Schema bin/rails lighthouse:print_schema > generated.graphql
400
+ FORMAT=json bin/rails lighthouse:print_schema # the introspection result
401
+ FORMAT=federation bin/rails lighthouse:print_schema # a subgraph's SDL, with @key, ...
402
+ bin/rails lighthouse:print_schema WRITE=1 # config.schema_output, else lighthouse-schema.graphql
403
+ bin/rails lighthouse:print_schema WRITE=schema.graphql # that file
358
404
  ```
359
405
 
360
- > The IDE reads fields as you wrote them: `users: [User!]! @paginate` still looks
361
- > like a list to it, although clients query `users { data { … } }`. Field
362
- > rewrites are not something an extra file can express.
406
+ graphql-ruby prints types, fields, arguments and enum values in alphabetical order,
407
+ so the output is stable (PHP Lighthouse's `--sort`). `WRITE` leaves an unchanged
408
+ file alone. For a codegen, let development keep the file up to date with
409
+ [`schema_output`](configuration.md#schema-output), and check it in CI with
410
+ `bin/rails lighthouse:schema_output:verify`.
411
+
412
+ The schema is the one of the environment it is printed in: a field with
413
+ `@show(env: ["development"])` is in development's and not in production's. Print
414
+ the file a production client relies on with `RAILS_ENV=production` when the schema
415
+ uses `@show` or `@hide`.
363
416
 
364
417
  ## Casing: camelCase ↔ snake_case
365
418
 
data/docs/performance.md CHANGED
@@ -117,6 +117,15 @@ config.persisted_queries_only = Rails.env.production?
117
117
  - The manifest's operations are served from memory, so a cache eviction can
118
118
  never drop them. The file is reloaded when it changes, and an id that is not
119
119
  the SHA-256 of its body is rejected.
120
+ - The manifest can also be a Hash of operations, or a callable answering a Hash
121
+ or a path, called for every persisted query: to read what a frontend build
122
+ (Vite, graphql-codegen's persisted documents) writes somewhere of its own. A Hash
123
+ is checked once, until its content changes; keep the callable cheap (memoize the
124
+ parsed file), as it runs per request.
125
+
126
+ ```ruby
127
+ config.persisted_queries_manifest = -> { ViteManifest.persisted_documents } # a Hash, memoized
128
+ ```
120
129
  - With `persisted_queries_only`, nothing else runs, and arbitrary queries get
121
130
  `Only persisted queries are allowed.` (`PERSISTED_QUERY_NOT_IN_LIST`).
122
131
 
data/docs/relay.md CHANGED
@@ -156,8 +156,12 @@ directives then work on them. The schema has one kind of global id and one `Node
156
156
  - `@globalId` on a field that resolves an object's own id encodes it with
157
157
  `id_from_object`: `Tag.id` answers `tag.to_gid_param`, as graphql-ruby's `Node.id`
158
158
  does. Any other value is encoded as before.
159
- - `@globalId` on an argument decodes with `object_from_id`, which loads the object.
160
- `ID` gives its id, and `ARRAY` / `TYPE` its class name (`["Tag", 1]`, `"Tag"`).
159
+ - `@globalId` on an argument decodes a Rails GlobalID without reading the database,
160
+ as PHP Lighthouse decodes its ids: `ID` gives its id, and `ARRAY` / `TYPE` its
161
+ model's name (`["Tag", "1"]`, `"Tag"`). So `tag(id: ID! @globalId(decode: ID) @eq):
162
+ Tag @find` runs the one query of `@find`, and a soft-deleted record's id decodes for
163
+ `@restore`. An id of another format (an `id_from_object` of your own) is decoded
164
+ with `object_from_id`, which loads the object.
161
165
  - `node:` is the SDL's `Node` interface: `interface Node`, which `@node` adds, and
162
166
  `implements Node` refer to `Types::NodeType`. A `@node` type implements it.
163
167
  - `Query.node` and `nodes` find objects with `object_from_id`, through the
data/docs/uploads.md CHANGED
@@ -20,10 +20,16 @@ type Mutation {
20
20
 
21
21
  Lighthouse reads its values itself (`Lighthouse::GraphQL::Upload`): the resolver gets
22
22
  the uploaded file, an `ActionDispatch::Http::UploadedFile`. A value that is not a file
23
- makes the argument invalid. `Upload` is for arguments only, never a field's result.
23
+ makes the argument invalid. An optional `Upload` (`avatar: Upload`) also takes `null`,
24
+ which the resolver gets as `nil`; leaving the argument out is not the same as sending
25
+ `null`. `Upload` is for arguments only, never a field's result.
24
26
 
25
27
  An ActiveStorage attachment takes the file as it is: with `has_one_attached :avatar`
26
- on `User`, the mutation above attaches it.
28
+ on `User`, the mutation above attaches it. This is the way to attach a file to a model:
29
+ ActiveStorage uploads it once the record is saved and the transaction committed, so a
30
+ mutation the model's validations refuse uploads nothing. Reach for `@upload` when the
31
+ argument needs the stored blob itself (its signed id), or a `path:` or service of its
32
+ own.
27
33
 
28
34
  ## `@upload`
29
35
 
@@ -51,6 +57,15 @@ The signed id is what an attachment attribute attaches (`user.avatar = signed_id
51
57
  `ActiveStorage::Blob.find_signed` finds; the blob keeps the file's name and content
52
58
  type. Lists of files are stored one by one, and `null` stays `null`.
53
59
 
60
+ `@upload` stores the file before the field resolves (after `@guard`, the `@can*`
61
+ directives and `@validator`), and the model validates it after. When the field fails,
62
+ because the model refuses it, or the resolver raises or reports an error, the blobs
63
+ `@upload` stored for it are purged before the response (a blob the service fails to
64
+ delete is left to ActiveStorage's purge job), so no blob and no file is left behind. A blob
65
+ that is stored but never attached (the field succeeds and does not attach it) stays,
66
+ as ActiveStorage's own direct uploads do: purge those with a periodic job over
67
+ `ActiveStorage::Blob.unattached`.
68
+
54
69
  ActiveStorage makes a whole service public (`public: true` in `config/storage.yml`)
55
70
  or private, never one file. So `public:` must agree with the service's, and the schema
56
71
  never says a file is private that anyone can read: `@upload(public: true)` on a private
@@ -76,6 +91,17 @@ updateAvatar(avatar: Upload! @upload(disk: "avatars", path: "users", public: tru
76
91
  `@upload` runs once `@guard`, the `@can*` family and `@validator` have let the call
77
92
  through, so a refused call stores nothing.
78
93
 
94
+ ## Serving the files: `@attachment`
95
+
96
+ [`@attachment`](directives.md#attachment) answers the URL of an attachment, loading
97
+ every parent's at once:
98
+
99
+ ```graphql
100
+ type User {
101
+ avatarUrl: String @attachment
102
+ }
103
+ ```
104
+
79
105
  ## The request
80
106
 
81
107
  ```shell
@@ -4,15 +4,17 @@
4
4
  # stitched schema:
5
5
  #
6
6
  # 1. DocumentAST.from_source: every type defined once.
7
- # 2. Type extensions merged into the types they extend. An extension of a
7
+ # 2. The SDL's definitions of graphql-ruby's built-in directives (@skip,
8
+ # @include, @deprecated, @oneOf, @specifiedBy) dropped: see BUILT_IN_DIRECTIVES.
9
+ # 3. Type extensions merged into the types they extend. An extension of a
8
10
  # root type that has no definition (`extend type Query` alone) defines it.
9
- # 3. The type and field manipulators: @hide/@show, @model, @paginate (and the
11
+ # 4. The type and field manipulators: @hide/@show, @model, @paginate (and the
10
12
  # relation directives' `type:`), @softDeletes, @node.
11
- # 4. The argument manipulators: each argument directive whose class includes
13
+ # 5. The argument manipulators: each argument directive whose class includes
12
14
  # Contracts::ArgManipulator rewrites its argument (@whereConditions,
13
15
  # @whereHasConditions, @orderBy turn `_` into the input types they generate).
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`).
16
+ # 6. `scalar _`, if the SDL declares it for the IDE, dropped: nothing is left of the placeholder.
17
+ # 7. The definitions of directives the generated types use (`@enum`).
16
18
  #
17
19
  # Returns the manipulated SDL; ManipulateAST listeners then see its document.
18
20
  module Lighthouse::GraphQL::ASTBuilder
@@ -41,10 +43,17 @@ module Lighthouse::GraphQL::ASTBuilder
41
43
 
42
44
  OBJECT_LIKE = [Nodes::ObjectTypeDefinition, Nodes::InterfaceTypeDefinition].freeze
43
45
 
46
+ # graphql-ruby's classes for these do the work: @skip skips, @oneOf makes the
47
+ # input object accept exactly one field. A definition in the SDL (copied from
48
+ # a printed schema, or from a graphql-js project, where it is harmless) would
49
+ # replace the class with a plain directive of the same name, which does nothing.
50
+ BUILT_IN_DIRECTIVES = ::GraphQL::Schema.default_directives.keys.freeze
51
+
44
52
  module_function
45
53
 
46
54
  def build(sdl, registry: Lighthouse::DirectiveRegistry.default)
47
55
  document_ast = Lighthouse::GraphQL::DocumentAST.from_source(sdl)
56
+ BUILT_IN_DIRECTIVES.each { |name| document_ast.remove_directive(name) }
48
57
  extend_types(document_ast)
49
58
 
50
59
  document_ast = Lighthouse::GraphQL::DocumentAST.from_source(registry.manipulate_sdl(document_ast.to_sdl))