Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to delete multiple items with GraphQL?

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.

like image 830
Mukhlis Kurnia Aji Avatar asked Feb 09 '17 06:02

Mukhlis Kurnia Aji


2 Answers

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.

like image 200
marktani Avatar answered Oct 19 '22 12:10

marktani


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.

like image 3
piotrbienias Avatar answered Oct 19 '22 14:10

piotrbienias