You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
After being validated, a GraphQL query is executed by a GraphQL server which returns a result that mirrors the shape of the requested query, typically as JSON.
5
+
<pclassName="learn-subtitle">Learn how GraphQL provides data for requested fields</p>
6
+
7
+
After a parsed document is [validated](/learn/validation/), a client's request will be [executed](https://spec.graphql.org/draft/#sec-Execution) by the GraphQL server and the returned result will mirror the shape of the requested query. On this page, you'll learn about the execution phase of GraphQL operations where data is read from or written to an existing source depending on what fields are requested by a client.
8
+
9
+
## Field resolvers
4
10
5
-
GraphQL cannot execute a query without a type system, let's use an example type system to illustrate executing a query. This is a part of the same type system used throughout the examples in these articles:
11
+
GraphQL cannot execute operations without a type system, so let's use an example type system to illustrate executing a query. This is a part of the same type system used throughout the examples in this guide:
@@ -41,66 +47,66 @@ In order to describe what happens when a query is executed, let's use an example
41
47
}
42
48
```
43
49
44
-
You can think of each field in a GraphQL query as a function or method of the previous type which returns the next type. In fact, this is exactly how GraphQL works. Each field on each type is backed by a function called the _resolver_ which is provided by the GraphQL server developer. When a field is executed, the corresponding _resolver_ is called to produce the next value.
50
+
You can think of each field in a GraphQL query as a function or method of the previous type which returns the next type. This is exactly how GraphQL works—each field on each type is backed by a _resolver function_ that is written by the GraphQL server developer. When a field is executed, the corresponding resolver is called to produce the next value.
45
51
46
-
If a field produces a scalar value like a string or number, then the execution completes. However if a field produces an object value then the query will contain another selection of fields which apply to that object. This continues until scalar values are reached. GraphQL queries always end at scalar values.
52
+
If a field produces a scalar value like a string or number, then the execution completes. However, if a field produces an object value then the query will contain another selection of fields that apply to that object. This continues until the leaf values are reached. GraphQL queries always end at Scalar or Enum types.
47
53
48
-
## Root fields & resolvers
54
+
## Root fields and resolvers
49
55
50
-
At the top level of every GraphQL server is a type that represents all of the possible entry points into the GraphQL API, it's often called the _Root_type or the _Query_ type.
56
+
At the top level of every GraphQL server is an Object type that represents the possible entry points into the GraphQL API, it's often called the `query` root operation type or the `Query` type. If the API supports mutations to write data and subscriptions to fetch real-time data as well, then it will have `Mutation` and `Subscription` types that expose fields to perform these kinds of operations too. You can learn more about these types on the [Schema and Types page](/learn/schema/#the-query-mutation-and-subscription-types).
51
57
52
-
In this example, our Query type provides a field called `human` which accepts the argument `id`. The resolver function for this field likely accesses a database and then constructs and returns a `Human`object.
58
+
In this example, our `Query` type provides a field called `human` which accepts the argument `id`. The resolver function for this field likely accesses a database and then constructs and returns a `Human`type:
53
59
54
60
```js
55
-
Query: {
56
-
human(obj, args, context, info) {
57
-
returncontext.db.loadHumanByID(args.id).then(
58
-
userData=>newHuman(userData)
59
-
)
60
-
}
61
+
functionQuery_human(obj, args, context, info) {
62
+
returncontext.db.loadHumanByID(args.id).then(
63
+
userData=>newHuman(userData)
64
+
)
61
65
}
62
66
```
63
67
64
-
This example is written in JavaScript, however GraphQL servers can be built in [many different languages](/code/). A resolver function receives four arguments:
68
+
This example is written in JavaScript, however, GraphQL servers can be built in [many different languages](/code/). The resolver function receives four arguments:
65
69
66
-
-`obj` The previous object, which for a field on the root Query type is often not used.
67
-
-`args` The arguments provided to the field in the GraphQL query.
68
-
-`context` A value which is provided to every resolver and holds important contextual information like the currently logged in user, or access to a database.
69
-
-`info` A value which holds field-specific information relevant to the current query as well as the schema details, also refer to [type GraphQLResolveInfo for more details](/graphql-js/type/#graphqlobjecttype).
70
+
-`obj`: The previous object (for a field on the root `Query` type, this argument is often not used).
71
+
-`args`: The arguments provided to the field in the GraphQL operation.
72
+
-`context`: A value provided to every resolver that may hold important contextual information like the currently logged in user, or access to a database.
73
+
-`info`: A value holding field-specific information relevant to the current operation as well as the schema details. Refer to [type GraphQLResolveInfo for more details](/graphql-js/type/#graphqlobjecttype).
74
+
75
+
<Callouttype="info">
76
+
Note that while a query operation could technically write data to the underlying data system during its execution, mutation operations are conventionally used for requests that produce side effects during their execution. And because mutation operations produce side effects, GraphQL implementations can be expected to execute these fields serially.
77
+
</Callout>
70
78
71
79
## Asynchronous resolvers
72
80
73
-
Let's take a closer look at what's happening in this resolver function.
81
+
Let's take a closer look at what's happening in this resolver function:
74
82
75
83
```js
76
-
human(obj, args, context, info) {
84
+
functionQuery_human(obj, args, context, info) {
77
85
returncontext.db.loadHumanByID(args.id).then(
78
86
userData=>newHuman(userData)
79
87
)
80
88
}
81
89
```
82
90
83
-
The `context` is used to provide access to a database which is used to load the data for a user by the `id`provided as an argument in the GraphQL query. Since loading from a database is an asynchronous operation, this returns a [Promise](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise). In JavaScript, Promises are used to work with asynchronous values, but the same concept exists in many languages, often called _Futures_, _Tasks_ or _Deferred_. When the database returns, we can construct and return a new `Human` object.
91
+
The `context` is used to provide access to a database. Specifically, the `id` argument in the GraphQL query is used to fetch data for a user. Since loading from a database is an asynchronous operation, this returns a [Promise](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise). In JavaScript, Promises are used to work with asynchronous values, but the same concept exists in many languages, often called _Futures_, _Tasks_, or _Deferred_. When the database returns the data, we can construct and return a new `Human` object.
84
92
85
-
Notice that while the resolver function needs to be aware of Promises, the GraphQL query does not. It simply expects the `human` field to return something which it can then ask the `name`of. During execution, GraphQL will wait for Promises, Futures, and Tasks to complete before continuing and will do so with optimal concurrency.
93
+
Notice that while the resolver function needs to be aware of Promises, the GraphQL query does not. It simply expects the `human` field to return something that can be further resolved to a scalar `name`value. During execution, GraphQL will wait for Promises, Futures, and Tasks to be completed before continuing and will do so with optimal concurrency.
86
94
87
95
## Trivial resolvers
88
96
89
-
Now that a `Human` object is available, GraphQL execution can continue with the fields requested on it.
97
+
Now that a `Human` object is available, GraphQL execution can continue with the fields requested for this type:
90
98
91
99
```js
92
-
Human: {
93
-
name(obj, args, context, info) {
94
-
returnobj.name
95
-
}
100
+
functionHuman_name(obj, args, context, info) {
101
+
returnobj.name
96
102
}
97
103
```
98
104
99
-
A GraphQL server is powered by a type system which is used to determine what to do next. Even before the `human` field returns anything, GraphQL knows that the next step will be to resolve fields on the `Human` type since the type system tells it that the `human` field will return a `Human`.
105
+
A GraphQL server is powered by a type system that is used to determine what to do next. Even before the `human` field returns anything, GraphQL knows that the next step will be to resolve fields on the `Human` type since the type system tells it that the `human` field will return this output type.
100
106
101
-
Resolving the name in this case is very straight-forward. The name resolver function is called and the `obj` argument is the `new Human` object returned from the previous field. In this case, we expect that Human object to have a `name` property which we can read and return directly.
107
+
Resolving the name in this case is straightforward. The name resolver function is called and the `obj` argument is the new `Human` object returned from the previous field. In this case, we expect this object to have a `name` property, which we can read and return directly.
102
108
103
-
In fact, many GraphQL libraries will let you omit resolvers this simple and will just assume that if a resolver isn't provided for a field, that a property of the same name should be read and returned.
109
+
Many GraphQL libraries will let you omit resolvers this simple and will assume that if a resolver isn't provided for a field, a property of the same name should be read and returned.
104
110
105
111
## Scalar coercion
106
112
@@ -114,39 +120,37 @@ Human: {
114
120
}
115
121
```
116
122
117
-
Notice that our type system claims `appearsIn` will return Enum values with known values, however this function is returning numbers! Indeed if we look up at the result we'll see that the appropriate Enum values are being returned. What's going on?
123
+
Notice that our type system claims `appearsIn` will return Enum types with known values, however, this function is returning numbers! Indeed if we look up at the result we'll see that the appropriate values for the Enum type are being returned. What's going on?
118
124
119
-
This is an example of scalar coercion. The type system knows what to expect and will convert the values returned by a resolver function into something that upholds the API contract. In this case, there may be an Enum defined on our server which uses numbers like `4`, `5`, and `6` internally, but represents them as Enum values in the GraphQL type system.
125
+
This is an example of _scalar coercion_. The type system knows what to expect and will convert the values returned by a resolver function into something that upholds the API contract. In this case, there may be an Enum type defined on our server that uses numbers like `4`, `5`, and `6` internally, but represents them as the expected values in the GraphQL type system.
120
126
121
127
## List resolvers
122
128
123
-
We've already seen a bit of what happens when a field returns a list of things with the `appearsIn` field above. It returned a _list_ of enum values, and since that's what the type system expected, each item in the list was coerced to the appropriate enum value. What happens when the `starships` field is resolved?
129
+
We've already seen some of what happens when a field returns a list of things with the `appearsIn` field above. It returned a [List type](/learn/schema/#lists) containing Enum type values, and since that's what the type system expected, each item in the list was coerced to the appropriate value. What happens when the `starships` field is resolved?
The resolver for this field is not just returning a Promise, it's returning a _list_ of Promises. The `Human` object had a list of ids of the `Starships` they piloted, but we need to go load all of those ids to get real Starship objects.
141
+
The resolver for this field is not just returning a Promise, it's returning a _list_ of Promises. The `Human` object had a list of IDs of the `Starships` they piloted, but we need to load all of those IDs to get real Starship objects.
138
142
139
-
GraphQL will wait for all of these Promises concurrently before continuing, and when left with a list of objects, it will concurrently continue yet again to load the `name` field on each of these items.
143
+
GraphQL will wait for all of these Promises concurrently before continuing, and when left with a list of objects, it will continue yet again to load the `name` field on each of these items concurrently.
140
144
141
145
## Producing the result
142
146
143
-
As each field is resolved, the resulting value is placed into a key-value map with the field name (or alias) as the key and the resolved value as the value. This continues from the bottom leaf fields of the query all the way back up to the original field on the root Query type. Collectively these produce a structure that mirrors the original query which can then be sent (typically as JSON) to the client which requested it.
147
+
As each field is resolved, the resulting value is placed into a key-value map with the field name (or alias) as the key and the resolved value as the value. This continues from the bottom leaf fields of the query back up to the original field on the root `Query` type. Collectively these produce a structure that mirrors the original query which can then be sent (typically as JSON) to the client that requested it.
144
148
145
149
Let's take one last look at the original query to see how all these resolving functions produce a result:
146
150
147
151
```graphql
148
152
# { "graphiql": true }
149
-
{
153
+
query{
150
154
human(id: 1002) {
151
155
name
152
156
appearsIn
@@ -156,3 +160,18 @@ Let's take one last look at the original query to see how all these resolving fu
156
160
}
157
161
}
158
162
```
163
+
164
+
As we can see, each field in the nested selection sets resolves to a scalar leaf value during execution of the query.
165
+
166
+
## Next steps
167
+
168
+
To recap what we've learned about execution:
169
+
170
+
- Each field in a GraphQL type system will have a corresponding resolver function that provides data for the field from an existing data source
171
+
- Execution begins at the top-level `query`, `mutation`, and `subscription` fields
172
+
- Resolvers may execute asynchronously
173
+
- Scalar coercion converts values into the types expected by the schema
174
+
- When a field on an Object type returns a List type of other objects, additional data may need to be fetched from the underlying data source to transform any foreign key-like references (such as IDs) into the related objects
175
+
- Once all of the requested fields have been resolved to the expected leaf values, the result is sent to the client, typically as JSON
176
+
177
+
Now that we understand how operations are executed, we can move to the last stage of the lifecycle of a GraphQL request where the [response](/learn/response/) is delivered to a client.
0 commit comments