Mutations in Apollo Kotlin
Mutations are GraphQL operations that modify back-end data. As a convention in GraphQL, queries are read operations and mutations are write operations.
Defining a mutation
You define a mutation in your app just like you define a query, except you use the mutation
keyword. Here's an example mutation for upvoting a post:
1mutation UpvotePost($postId: Int!) {
2 upvotePost(postId: $postId) {
3 id
4 votes
5 }
6}
And here's an example schema snippet that supports this mutation:
1type Mutation {
2 upvotePost(postId: Int!): Post
3}
4
5type Post {
6 id: Int!
7 votes: Int!
8 content: String!
9}
The fields of the Mutation
type (such as upvotePost
above) usually describe the actions that mutations can perform. These fields usually take one or more arguments, which specify the data to create or modify.
Mutation return types
The return type of a Mutation
field usually includes the backend data that's been modified. This provides the requesting client with immediate information about the result of the mutation.
In the example above, upvotePost
returns the Post
object that's just been upvoted. Here's an example response:
1{
2 "data": {
3 "upvotePost": {
4 "id": "123",
5 "votes": 5
6 }
7 }
8}
For more information on mutation return types, see Designing mutations.
Generating mutation classes
Similar to queries, mutations are represented by instances of generated classes, conforming to the Mutation
interface.
Constructor arguments are used to define mutation variables. You pass a mutation object
to ApolloClient#mutation(mutation)
to send the mutation to the server, execute it, and receive typed results:
1val upvotePostMutation = UpvotePostMutation(postId = 3)
2
3val response = try {
4 apolloClient.mutation(upvotePostMutation).execute()
5} catch(e: ApolloException) {
6 // handle error
7}
Using fragments in mutation results
In many cases, you'll want to use mutation results to update your UI. Fragments are a great way to share result handling between queries and mutations:
1mutation UpvotePost($postId: Int!) {
2 upvotePost(postId: $postId) {
3 ...PostDetails
4 }
5}
Passing input objects
The GraphQL type system includes input objects as a way to pass complex values to fields. Input objects are often used for mutation variables, because they provide a compact way to pass in objects to be created:
1mutation CreateReviewForEpisode($episode: Episode!, $review: ReviewInput!) {
2 createReview(episode: $episode, review: $review) {
3 stars
4 commentary
5 }
6}
1val reviewInput = ReviewInput(stars = 5, commentary = "This is a great movie!")
2
3try {
4 val response = apolloClient.mutation(CreateReviewForEpisodeMutation(episode = Episode.NEWHOPE, review = reviewInput)).execute()
5} catch (e: ApolloException) {
6 // handle exception
7}