Reputation: 272
I know that in GraphQL: Query
is used when you want to read some data from the server while Mutation
is used when you want to write data back to the server.
But can’t I go to the resolver in the query and do a write operation.
I don't know why we need to separate the read the write operations and hence mutations are needed.
Upvotes: 1
Views: 821
Reputation: 84777
From the spec:
There are three types of operations that GraphQL models:
- query – a read‐only fetch.
- mutation – a write followed by a fetch.
- subscription – a long‐lived request that fetches data in response to source events.
Because it's up to each GraphQL service to provide the actual field resolution logic, it's obviously possible to create queries with side-effects and mutations that are actually only read-only operations. The distinction between queries and mutations is largely one based around convention and client expectations -- queries are intended to be "safe" operations similar to how GET requests are "safe".
There is a single major difference in how these two operations are executed though -- the selection set for a query can be resolved in parallel, while the selection set for a mutation is always resolved serially.
So in a query like
query {
foo
bar
}
foo
and bar
will resolve at the same time. On the other hand, here
mutation {
foo
bar
}
foo
will resolve first followed by bar
.
This is an important feature because it allows a client to send multiple mutations that are dependent on one another (for example, an insert followed by an update). Normally, parallel execution of fields is a good thing as it shortens the response time, but here sequential execution can be a desirable feature.
On a practical side note, it's important to keep in mind that clients often make certain assumptions about app behavior depending on the operation type of a particular operation as well. For example, react-apollo
assumes queries should be ran when a component mounts, while assuming mutations are something to be triggered by a user action.
Upvotes: 3