Skip to content

Commit 38e3d17

Browse files
mandiwisebenjie
andauthored
Update validation page. (graphql#1803)
Co-authored-by: Benjie <[email protected]>
1 parent a11ee00 commit 38e3d17

File tree

1 file changed

+82
-89
lines changed

1 file changed

+82
-89
lines changed

src/pages/learn/validation.mdx

Lines changed: 82 additions & 89 deletions
Original file line numberDiff line numberDiff line change
@@ -1,97 +1,47 @@
11
# Validation
22

3-
By using the type system, it can be predetermined whether a GraphQL query
4-
is valid or not. This allows servers and clients to effectively inform
5-
developers when an invalid query has been created, without having to rely
6-
on runtime checks.
3+
<p className="learn-subtitle">Learn how GraphQL validates operations using a schema</p>
74

8-
For our Star Wars example, the file
9-
[starWarsValidation-test.ts](https://github.com/graphql/graphql-js/blob/main/src/__tests__/starWarsValidation-test.ts)
10-
contains a number of queries demonstrating various invalidities, and is a test
11-
file that can be run to exercise the reference implementation's validator.
5+
On this page, we'll explore an important phase in the lifecycle of a GraphQL request called [validation](https://spec.graphql.org/draft/#sec-Validation). A request must be syntactically correct to run, but it should also be valid when checked against the API's schema.
126

13-
To start, let's take a complex valid query. This is a nested query, similar to
14-
an example from the previous section, but with the duplicated fields factored
15-
out into a fragment:
7+
In practice, when a GraphQL operation reaches the server, the document is first parsed and then validated using the type system. This allows servers and clients to effectively inform developers when an invalid query has been created, without relying on runtime checks. Once the operation is validated, it can be [executed](/learn/execution/) on the server and a response will be delivered to the client.
168

17-
```graphql
18-
# { "graphiql": true }
19-
{
20-
hero {
21-
...NameAndAppearances
22-
friends {
23-
...NameAndAppearances
24-
friends {
25-
...NameAndAppearances
26-
}
27-
}
28-
}
29-
}
9+
## Validation examples
3010

31-
fragment NameAndAppearances on Character {
32-
name
33-
appearsIn
34-
}
35-
```
11+
The GraphQL specification describes the detailed conditions that must be satisfied for a request to be considered valid. In the sections that follow, we'll look at a few examples of common validation issues that may occur in GraphQL operations.
3612

37-
And this query is valid. Let's take a look at some invalid queries...
13+
### Requesting non-existent fields
3814

39-
A fragment cannot refer to itself or create a cycle, as this could result in
40-
an unbounded result! Here's the same query above but without the explicit three
41-
levels of nesting:
42-
43-
```graphql
44-
# { "graphiql": true }
45-
{
46-
hero {
47-
...NameAndAppearancesAndFriends
48-
}
49-
}
50-
51-
fragment NameAndAppearancesAndFriends on Character {
52-
name
53-
appearsIn
54-
friends {
55-
...NameAndAppearancesAndFriends
56-
}
57-
}
58-
```
59-
60-
When we query for fields, we have to query for a field that exists on the
61-
given type. So as `hero` returns a `Character`, we have to query for a field
62-
on `Character`. That type does not have a `favoriteSpaceship` field, so this
63-
query is invalid:
15+
When we query for a field, the field must be defined on the relevant type. As `hero` returns a `Character` type, its selection set may only request the `Character` type's fields; `Character` does not have a `favoriteSpaceship` field, so this query is invalid:
6416

6517
```graphql
6618
# { "graphiql": true }
6719
# INVALID: favoriteSpaceship does not exist on Character
68-
{
20+
query {
6921
hero {
7022
favoriteSpaceship
7123
}
7224
}
7325
```
7426

75-
Whenever we query for a field and it returns something other than a scalar
76-
or an enum, we need to specify what data we want to get back from the field.
77-
Hero returns a `Character`, and we've been requesting fields like `name` and
78-
`appearsIn` on it; if we omit that, the query will not be valid:
27+
### Selection sets and leaf fields
28+
29+
Whenever we query for a field and it returns something other than a Scalar or Enum type, we need to specify what data we want to get back from the field (a "selection set"). The `hero` query field returns a `Character`, and we've already seen examples that request fields like `name` and `appearsIn` on it. If we omit those leaf field selections, then the query will not be valid:
7930

8031
```graphql
8132
# { "graphiql": true }
8233
# INVALID: hero is not a scalar, so fields are needed
83-
{
34+
query {
8435
hero
8536
}
8637
```
8738

88-
Similarly, if a field is a scalar, it doesn't make sense to query for
89-
additional fields on it, and doing so will make the query invalid:
39+
Similarly, querying fields of a scalar or enum doesn’t make sense, therefore adding a selection set to a leaf field will make the query invalid:
9040

9141
```graphql
9242
# { "graphiql": true }
9343
# INVALID: name is a scalar, so fields are not permitted
94-
{
44+
query {
9545
hero {
9646
name {
9747
firstCharacterOfName
@@ -100,32 +50,26 @@ additional fields on it, and doing so will make the query invalid:
10050
}
10151
```
10252

103-
Earlier, it was noted that a query can only query for fields on the type
104-
in question; when we query for `hero` which returns a `Character`, we
105-
can only query for fields that exist on `Character`. What happens if we
106-
want to query for R2-D2s primary function, though?
53+
### Missing fragments for fields that output abstract types
54+
55+
Earlier, it was noted that a query can only ask for fields on the type in question. So when we query for `hero` which returns a `Character`, we can only request fields that exist on the `Character` Interface type. What happens if we want to query for R2-D2's primary function, though?
10756

10857
```graphql
10958
# { "graphiql": true }
11059
# INVALID: primaryFunction does not exist on Character
111-
{
60+
query {
11261
hero {
11362
name
11463
primaryFunction
11564
}
11665
}
11766
```
11867

119-
That query is invalid, because `primaryFunction` is not a field on `Character`.
120-
We want some way of indicating that we wish to fetch `primaryFunction` if the
121-
`Character` is a `Droid`, and to ignore that field otherwise. We can use
122-
the fragments we introduced earlier to do this. By setting up a fragment defined
123-
on `Droid` and including it, we ensure that we only query for `primaryFunction`
124-
where it is defined.
68+
That query is invalid, because `primaryFunction` is not one of the shared fields defined by the `Character` Interface type. We want some way of indicating that we wish to fetch `primaryFunction` if the `Character` is a `Droid`, and to ignore that field otherwise. We can use the [fragments](/learn/queries/#fragments) to do this. By setting up a fragment defined on `Droid` and including it in the selection set, we ensure that we only query for `primaryFunction` where it is defined:
12569

12670
```graphql
12771
# { "graphiql": true }
128-
{
72+
query {
12973
hero {
13074
name
13175
...DroidFields
@@ -137,15 +81,11 @@ fragment DroidFields on Droid {
13781
}
13882
```
13983

140-
This query is valid, but it's a bit verbose; named fragments were valuable
141-
above when we used them multiple times, but we're only using this one once.
142-
Instead of using a named fragment, we can use an inline fragment; this
143-
still allows us to indicate the type we are querying on, but without naming
144-
a separate fragment:
84+
This query is valid, but it's a bit verbose; named fragments were valuable above when we used them multiple times, but we're only using this one once. Instead of using a named fragment, we can use an [inline fragment](/learn/queries/#inline-fragments); this still allows us to indicate the type we are querying on, but without naming a separate fragment:
14585

14686
```graphql
14787
# { "graphiql": true }
148-
{
88+
query {
14989
hero {
15090
name
15191
... on Droid {
@@ -155,10 +95,63 @@ a separate fragment:
15595
}
15696
```
15797

158-
This has just scratched the surface of the validation system; there
159-
are a number of validation rules in place to ensure that a GraphQL query
160-
is semantically meaningful. The specification goes into more detail about this
161-
topic in the "Validation" section, and the
162-
[validation](https://github.com/graphql/graphql-js/blob/main/src/validation)
163-
directory in GraphQL.js contains code implementing a
164-
specification-compliant GraphQL validator.
98+
### Cyclic fragment spreads
99+
100+
To start, let's take a complex valid query. This is a nested query, but with the duplicated fields factored out into a fragment:
101+
102+
```graphql
103+
# { "graphiql": true }
104+
query {
105+
hero {
106+
...NameAndAppearances
107+
friends {
108+
...NameAndAppearances
109+
friends {
110+
...NameAndAppearances
111+
}
112+
}
113+
}
114+
}
115+
116+
fragment NameAndAppearances on Character {
117+
name
118+
appearsIn
119+
}
120+
```
121+
122+
The following is an alternative to the above query, attempting to use recursion instead of the explicit three levels of nesting. This new query is invalid because a fragment cannot refer to itself (directly or indirectly) since the resulting cycle could create an unbounded result!
123+
124+
```graphql
125+
# { "graphiql": true }
126+
query {
127+
hero {
128+
...NameAndAppearancesAndFriends
129+
}
130+
}
131+
132+
fragment NameAndAppearancesAndFriends on Character {
133+
name
134+
appearsIn
135+
friends {
136+
...NameAndAppearancesAndFriends
137+
}
138+
}
139+
```
140+
141+
This has just scratched the surface of the validation system; there are a number of validation rules in place to ensure that a GraphQL operation is semantically meaningful. The specification goes into more detail about this topic in the [validation section](https://spec.graphql.org/draft/#sec-Validation), and the [validation directory in the reference implementation](https://github.com/graphql/graphql-js/blob/main/src/validation) contains code implementing a specification-compliant GraphQL validator.
142+
143+
## Validation errors
144+
145+
As we have seen in the examples above, when a GraphQL server encounters a validation error in a request, it will return information about what happened in the `errors` key of the response. Specifically, when GraphQL detects a validation issue in a document, it raises a _request error_ before execution begins, meaning that no partial data will be included in the response.
146+
147+
And because the GraphQL specification requires all implementations to validate incoming requests against the schema, developers won't need to write specific runtime logic to handle these validation issues manually.
148+
149+
## Next steps
150+
151+
To recap what we've learned about validation:
152+
153+
- To be executed, requests must include a syntactically correct document that is considered valid when checked against the schema
154+
- The specification requires implementations check incoming requests contain valid field selections, correct fragment usage, and more
155+
- When a validation issue occurs, the server will raise a request error and return to the client information about what happened; field execution will not start
156+
157+
Head over to the [Execution](/learn/execution/) page to learn how GraphQL provides data for each field in a request after the validation step successfully completes.

0 commit comments

Comments
 (0)