I am new in GraphQL. How can I write a delete mutation to delete multiple items (more than one ID) in GraphQL? I use scaphold.io.
You can batch multiple mutations in the same request to the GraphQL server using GraphQL aliases.
Let's say this is how you delete one Item:
mutation deleteOne {
deleteItem(id: "id1") {
id
}
}
Then this is how you can delete multiple items in one request:
mutation deleteMultiple {
id1: deleteItem(id: "id1") {
id
}
id2: deleteItem(id: "id2") {
id
}
# ... and so on
id100: deleteItem(id: "id100") {
id
}
}
It's helpful to know that multiple mutations in one request run sequentially in the stated order (from top to bottom). You can also run multiple queries in one request the same way, and multiple queries in one request run in parellel.
If you want to run say 1000 mutations, it might be better to batch them in 10 groups of 100.
More information and another example can be found in this FAQ article as well as the official GraphQL docs.
I think that good solution would be to create a method (mutation) that accepts array of e.g. IDs, that are further used to batch delete multiple records from the database.
mutation deleteUsers($userIds: [Int!]!) {
deleteUsers(userIds: $userIds) {
...
}
}
Then, in the resolver you could use the userIds
parameter to perform an SQL query like DELETE FROM users WHERE id IN userIds
, where userIds
of course should be correctly replaced (escaped), depending on how you interact with the database.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With