graphql-request icon indicating copy to clipboard operation
graphql-request copied to clipboard

Add Support for Batching Mutations

Open ricbermo opened this issue 3 years ago • 3 comments

Perceived Problem

I was trying to delete multiple records at once but I noticed my "documents" are sent as queries

const requests = uuids.map((uuid: string) => ({
  document: deleteRecordById,
    variables: {uuid},
  }));
await client.batchRequests(requests);

// export const deleteRecordById = `
mutation deleteRecordById($uuid: ID!) {
  deleteRecordById(id: $uuid) {
    id
  }
}`;

Ideas / Proposed Solution(s)

It'd be nice to let batchRequests work for mutations as well. For now, this is what I did

const request = uuids.map((uuid: string) =>
  client.request(deleteChildAthleteById, {uuid}),
);
await Promise.all(request);

Thanks

ricbermo avatar Apr 28 '23 11:04 ricbermo

For the time being one can use:

const batchRequests = async (requests) => Promise.all(requests.map((request) => mutationClient.request(request.document, request.variables)))

DanielAtCosmicDNA avatar Jun 08 '23 18:06 DanielAtCosmicDNA

The downside with this workaround is that it's not really batching requests since multiple requests are sent albeit in parallel.

goleary avatar Jun 26 '23 21:06 goleary

The downside with this workaround is that it's not really batching requests since multiple requests are sent albeit in parallel.

The idea is to use this in the meanwhile there is no graphql-request working feature that contemplates batching mutations. Once graphql-request develops the feature, it is just the matter of using graphql-request's batchRequests as a drop-in replacement for this workaround.

DanielAtCosmicDNA avatar Jun 27 '23 09:06 DanielAtCosmicDNA

Graffle has batch support in the sense that graphQL does. For example you can do this in GraphQL:

  mutation {
    deleteUser1: deleteUser(id:"abc1")
    deleteUser2: deleteUser(id:"abc2")
    deleteUser3: deleteUser(id:"abc3")
    deleteUser4: deleteUser(id:"abc4")
    # ...
  }

This is run serially on the server which may not be what you want. Interestingly you could run them in parallel by using nested fields:

  mutation {
    delete: {
	    user1: user(id:"abc1")
	    user2: user(id:"abc2")
	    user3: user(id:"abc3")
	    user4: user(id:"abc4")
	    # ...
    }
  }

Now those deletes would be executed in parallel by the server.

I understand there is also the concept of HTTP Request batching wherein multiple GraphQL documents are sent in ONE HTTP body. My understanding is Apollo originally pioneered this approach or at least popularized it. Graffle should eventually support this but not immediately unless there is major user requests. The new feature is being tracked at https://github.com/jasonkuhrt/graphql-request/issues/1017.

jasonkuhrt avatar Aug 04 '24 16:08 jasonkuhrt