Mutations: Modifying Your Data
6 min read
Mutations: Modifying Your Data 🍫
Welcome back! So far, we've been on a grand tour of fetching data with GraphQL. But what happens when we want to change something? Add a new user, update a product, or delete a comment? That's where Mutations come in, and they're the star of today's show.
Think of it like this: if queries are for reading data, mutations are for writing data. They are the C, U, and D in your classic CRUD (Create, Read, Update, Delete) operations.
1. Understanding Mutations: Create, Update, Delete ✏️
At its core, a mutation is a GraphQL operation that modifies data on the server. While a query is all about asking for information, a mutation is about making a change. In the world of REST, you might be used to POST, PUT, PATCH, and DELETE requests. Mutations in GraphQL cover all these actions.
The Problem: How do we tell our server to change data in a structured and predictable way?
The Solution: We define specific Mutation types in our GraphQL schema that explicitly state what changes are possible.
Let's imagine we're building a simple blogging application. We'll need to be able to create new posts, update existing ones, and delete them.
Creating a New Post:
To create a new post, we'd define a createPost mutation.
Schema Definition (schema.graphql):
type Mutation {
createPost(title: String!, content: String!): Post
}
type Post {
id: ID!
title: String!
content: String!
}In this schema, our createPost mutation takes a title and content as arguments (the ! means they are required) and returns the newly created Post.
Mutation Operation:
mutation {
createPost(title: "My First Post", content: "This is the content of my first post.") {
id
title
content
}
}When this mutation is sent to the server, it will trigger the corresponding resolver function to create a new post and then return the specified fields (id, title, and content) of that new post.
Updating a Post:
To update an existing post, we might have an updatePost mutation.
Schema Definition:
type Mutation {
updatePost(id: ID!, title: String, content: String): Post
}Notice here that title and content are optional. This allows us to update only one of them if we want to.
Mutation Operation:
mutation {
updatePost(id: "some-post-id", title: "My Updated Post Title") {
id
title
}
}Deleting a Post:
And to delete a post, a deletePost mutation.
Schema Definition:
type Mutation {
deletePost(id: ID!): ID
}A common practice for delete mutations is to return the ID of the deleted item to confirm the operation was successful.
Mutation Operation:
mutation {
deletePost(id: "some-post-id")
}Fun Fact: While query fields are designed to be executed in parallel by the GraphQL engine, mutation fields run in series, one after the other. This ensures that your data modifications happen in a predictable order.
2. Input Types: Structuring Complex Arguments 📦
As our mutations get more complex, we might find ourselves with a long list of arguments.
The Problem: Passing many arguments to a mutation can become cumbersome and hard to read.
The Solution: GraphQL's input types allow us to bundle arguments into a single object.
Imagine our createPost mutation also needed to accept a category, tags, and an author ID. Without input types, it would look like this:
type Mutation {
createPost(
title: String!,
content: String!,
categoryId: ID!,
tags: [String!]!,
authorId: ID!
): Post
}This can get out of hand quickly. Let's refactor this using an input type.
Schema Definition with Input Type:
input CreatePostInput {
title: String!
content: String!
categoryId: ID!
tags: [String!]!
authorId: ID!
}
type Mutation {
createPost(input: CreatePostInput!): Post
}Now, our mutation is much cleaner. We pass a single input argument of type CreatePostInput.
Mutation Operation with Input Type:
mutation CreateNewPost($newPostData: CreatePostInput!) {
createPost(input: $newPostData) {
id
title
}
}And the variables would be a separate JSON object:
{
"newPostData": {
"title": "A Post with Input Types",
"content": "This is so much cleaner!",
"categoryId": "cat-123",
"tags": ["graphql", "mutations"],
"authorId": "author-456"
}
}Using a single, required input object for mutations is a widely adopted best practice.
3. The Payload: Returning Useful Data After a Change 🎁
After a mutation completes, what should it return?
The Problem: How does the client know the result of the mutation and what data has changed?
The Solution: Mutations should return a payload object that contains the modified data. This is crucial for client-side state management, as it avoids the need for a follow-up query to fetch the updated information.
A good practice is to design a unique payload type for each mutation. This makes your API more evolvable.
Schema Definition with a Payload Type:
Instead of directly returning a Post, we can return a CreatePostPayload.
type CreatePostPayload {
post: Post
success: Boolean!
message: String
}
type Mutation {
createPost(input: CreatePostInput!): CreatePostPayload!
}Mutation Operation:
mutation {
createPost(input: { title: "Payloads are Awesome", content: "..." }) {
success
message
post {
id
title
}
}
}This approach gives the client more information about the result of the mutation. They immediately get the new post object, a success flag, and a helpful message.
4. Handling Expected Errors in Mutations 🚨
Things don't always go as planned. What if a user tries to update a post that doesn't exist?
The Problem: How do we communicate predictable errors to the client in a structured way?
The Solution: We can include a field for user-facing errors in our mutation payload. This is often referred to as treating "errors as data."
Let's enhance our UpdatePostPayload to handle a "post not found" error.
Schema Definition with Error Handling:
type UpdatePostPayload {
post: Post
userErrors: [UserError!]!
}
type UserError {
message: String!
field: String
}
type Mutation {
updatePost(id: ID!, title: String): UpdatePostPayload!
}Now, if the updatePost resolver can't find the post, it won't throw a generic server error. Instead, it will return a UpdatePostPayload with an empty post and a descriptive userErrors array.
Successful Mutation Response:
{
"data": {
"updatePost": {
"post": {
"id": "some-post-id",
"title": "My Updated Title"
},
"userErrors": []
}
}
}Error Response:
{
"data": {
"updatePost": {
"post": null,
"userErrors": [
{
"message": "Could not find a post with that ID.",
"field": "id"
}
]
}
}
}This approach provides a much better experience for the developer on the client side, allowing them to gracefully handle predictable errors in the UI.
Further Reading & References 📚
- Official GraphQL Documentation on Mutations: https://graphql.org/learn/mutations/
- Apollo GraphQL Documentation on Mutations: https://www.apollographql.com/docs/react/data/mutations/
- Best Practices for GraphQL Mutations: https://www.apollographql.com/blog/graphql/basics/designing-graphql-mutations/
Challenge
You are tasked with designing a GraphQL mutation for an e-commerce application. Your goal is to define the schema for updating the quantity of an item in a user's shopping cart.
Your schema must follow modern best practices by incorporating dedicated input types, payload types, and a structured way to handle user-facing errors.
Requirements:
- Define a
UserErrortype: This type will be used to communicate predictable errors. It must contain:field: AStringindicating which input field caused the error.message: A non-nullableStringdescribing the error.
- Define an
UpdateCartItemInputinput type: This will bundle all arguments for the mutation. It must contain:cartItemId: The non-nullableIDof the cart item to update.quantity: The new non-nullableIntquantity for the item.
- Define an
UpdateCartItemPayloadtype: This will be the return type for the mutation. It must contain:success: A non-nullableBooleanindicating if the operation was successful.message: A non-nullableStringproviding a human-readable summary of the outcome.cartItem: The updatedCartItemobject. This can be null if the operation failed.userErrors: A non-nullable list of non-nullableUserErrorobjects.
- Define the
Mutationtype: It should have a single field:updateCartItem: This mutation accepts one non-nullable argument,inputof typeUpdateCartItemInput, and returns a non-nullableUpdateCartItemPayload.
Expected result
Your submitted schema should define four new types: UserError, UpdateCartItemInput, UpdateCartItemPayload, and Mutation.
The final schema should contain the following definitions:
# The UserError type for structured, user-facing errors.
type UserError {
field: String
message: String!
}
# The input type to bundle arguments for the mutation.
input UpdateCartItemInput {
cartItemId: ID!
quantity: Int!
}
# The payload type returned by the mutation.
type UpdateCartItemPayload {
success: Boolean!
message: String!
cartItem: CartItem
userErrors: [UserError!]!
}
# The root Mutation type defining the update operation.
type Mutation {
updateCartItem(input: UpdateCartItemInput!): UpdateCartItemPayload!
}