How to delete multiple items with GraphQL?
Asked Answered
B

2

8

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.

Bolster answered 9/2, 2017 at 6:22 Comment(0)
E
16

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.

Eructate answered 9/2, 2017 at 8:29 Comment(2)
Link to FAQ article is broken.Leafstalk
adding multiple delete is not possible , if i delete 100 ?Kelwunn
V
3

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.

Veto answered 9/2, 2017 at 11:37 Comment(1)
it works but how can you return the multiple objects that have been deleted with the GraphQL mutation, so that you can build a log message such as : "X, Y, and Z have been deleted" ?Liard

© 2022 - 2024 — McMap. All rights reserved.