Question
Answer and Explanation
Deleting data through a GraphQL query involves using a mutation, not a query. Queries are for fetching data, while mutations are for modifying data, including deletions. Here's how you can achieve this:
1. Define a GraphQL Mutation:
- You need to define a mutation in your GraphQL schema that specifies how to delete data. This mutation will typically take an identifier (like an ID) as an argument to specify which record to delete.
2. Example GraphQL Schema (SDL):
type Mutation {
deleteUser(id: ID!): DeletePayload
}
type DeletePayload {
success: Boolean!
message: String
}
- In this example, deleteUser
is the mutation that takes a required id
argument and returns a DeletePayload
object indicating the success or failure of the deletion.
3. Implement the Resolver:
- The resolver function for the deleteUser
mutation will contain the logic to delete the data from your database. This typically involves using your database's API to remove the record based on the provided ID.
4. Example Resolver (Node.js with Mongoose):
const resolvers = {
Mutation: {
deleteUser: async (_, { id }) => {
try {
await User.findByIdAndDelete(id);
return { success: true, message: "User deleted successfully" };
} catch (error) {
console.error("Error deleting user:", error);
return { success: false, message: "Failed to delete user" };
}
},
},
};
- This resolver uses Mongoose to find and delete a user by ID. It returns a success or failure message.
5. Send the GraphQL Mutation:
- Use a GraphQL client (like Apollo Client, Relay, or a simple fetch request) to send the mutation to your GraphQL server.
6. Example GraphQL Mutation Request:
mutation {
deleteUser(id: "user-id-to-delete") {
success
message
}
}
- Replace "user-id-to-delete"
with the actual ID of the record you want to delete.
7. Handle the Response:
- Your client will receive a response containing the success
and message
fields from the DeletePayload
. Use this to update your UI or handle any errors.
By following these steps, you can effectively delete data using a GraphQL mutation. Remember that the specific implementation details will vary depending on your GraphQL server setup and database.