In GraphQL, mutations are used to modify the server-side data. They allow us to perform operations like creating new data, updating existing data, and deleting data. Mutations in GraphQL are analogous to POST, PUT, and DELETE requests in REST APIs.
To create new data in GraphQL, we typically use a mutation operation with a specific name, input arguments representing the data to be created, and a return type indicating the fields we want to receive back.
mutation {
createPost(input: { title: "New Post", content: "Lorem ipsum dolor sit amet." }) {
id
title
content
}
}
In this example, we are creating a new post with a title and content. The server will respond with the id
, title
, and content
of the newly created post.
When it comes to updating data, GraphQL provides mutation operations that allow us to modify specific fields of an existing object. We can specify the fields we want to update, along with their new values.
mutation {
updatePost(id: "abc123", input: { title: "Updated Post", content: "Updated content." }) {
id
title
content
}
}
This example demonstrates updating a post with the ID abc123
by changing its title and content. The server will return the updated values for id
, title
, and content
.
To delete data with GraphQL, we use a mutation operation specifying the ID of the object we want to delete. The server will typically respond with a success message or an error if the deletion fails.
mutation {
deletePost(id: "abc123")
}
In the above example, we are deleting a post with the ID abc123
. The server will simply respond with a true
value indicating the successful deletion.
These are the basics of mutations and input types in GraphQL. They allow us to manipulate data on the server-side with ease and granularity. Remember to handle errors and validate inputs properly to ensure the integrity of your data.
Keep learning and exploring the power of GraphQL! You are on your way to becoming a GraphQL pro! 🚀