0
votes

I have defined a mutation which lets users duplicate their products, one product at a time:

mutation DuplicateProduct($productID: ID!) {
  duplicateProduct(productID: $productID) {
    id
  }
}

Now I have to implement a feature, which would allow users to duplicate multiple products at once.

One obvious solution is to redesign the schema to accept multiple product IDs. I'd like to avoid that work if possible.

Another option is to simply post the same mutation multiple times in a row, but it appears that with the way CodeGen generates the mutation services, I'd have to send multiple separate HTTP requests.

My question is this: is it possible to batch a dynamic number of mutations in a single request using the CodeGen-generated services? It seems like batching would be easy if I didn't use CodeGen, since I could just create the mutation definition dynamically on the fly. However, CodeGen seems to enforce rather static operation definitions.

Is there a nice way to achieve what I am looking for? I might be going the wrong way about this too, so if the most graphql-y solution actually requires a schema redesign, I'd be happy if someone pointed this out to me.types

2

2 Answers

2
votes

Think of codegen as development tool, not as runtime library, so it should provide typings and generate code. The functionality you mentioned refers to the runtime behaviour of you app.

GraphQL-Codegen doesn't deal with this kind of functionality, but you can create a custom plugin that will create the grouped operations you need (https://graphql-code-generator.com/docs/custom-codegen/index).

I think the best way to group operation in runtime is to use batching solution. If you are using Apollo-Client, you can use apollo-link-batch-http (https://www.apollographql.com/docs/link/links/batch-http/) and it will group GraphQL operations that are executed together (you can customize the timespan).

0
votes

The optimal solution is to create a new mutation field to support this functionality, because that way you can optimize how your application does the actual write operation (i.e. a single database call instead of multiple). In the event that your data source requires you to make multiple requests to it for each product regardless, you may want to be able to undo all the work that was done if any individual operation fails.

Assuming you're using Apollo client, you can also use a link that does batching so that even if you make separate calls to the mutation service, they'll be batched into a single GraphQL request.

If you need some way to do dynamic operations with codegen, you can submit a feature request issue. However, this seems like an edge case -- if the schema is missing functionality the client needs, then its best to try to implement that functionality in the schema rather than trying to solve it on the client-side. If you solve it client-side, you'll have to do it once for every client application you have.