Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can i run one mutation multiple times with different arguments in one request?

I have a mutation:

const createSomethingMutation = gql`
  mutation($data: SomethingCreateInput!) {
    createSomething(data: $data) {
      something {
        id
        name
      }
    }
  }
`;

How do I create many Somethings in one request? Do I need to create a new Mutation on my GraphQL server like this:

mutation {
  addManySomethings(data: [SomethingCreateInput]): [Something]
} 

Or is there a way to use the one existing createSomethingMutation from Apollo Client multiple times with different arguments in one request?

like image 330
Maxim Zubarev Avatar asked Jun 16 '18 16:06

Maxim Zubarev


People also ask

What is the difference between a query and a mutation?

A mutation can contain multiple fields, just like a query. There's one important distinction between queries and mutations, other than the name: While query fields are executed in parallel, mutation fields run in series, one after the other.

What is useMutation in react query?

useMutation will track the state of a mutation, just like useQuery does for queries. It'll give you loading, error and status fields to make it easy for you to display what's going on to your users. You'll also get the same nice callbacks that useQuery has: onSuccess, onError and onSettled.

What is Upsert in GraphQL?

Upsert mutations allow you to perform add or update operations based on whether a particular ID exists in the database. The IDs must be external IDs, defined using the @id directive in the schema. For example, to demonstrate how upserts work in GraphQL, take the following schema: Schema. type Author { id: String! @


1 Answers

You can in fact do this using aliases, and separate variables for each alias:

const createSomethingMutation = gql`
  mutation($dataA: SomethingCreateInput!) {
    createA: createSomething(data: $dataA) {
      something {
        id
        name
      }
    }
    createB: createSomething(data: $dataB) {
      something {
        id
        name
      }
    }
  }
`;

You can see more examples of aliases in the spec.

Then you just need to provide a variables object with two properties -- dataA and dataB. Things can get pretty messy if you need the number of mutations to be dynamic, though. Generally, in cases like this it's probably easier (and more efficient) to just expose a single mutation to handle creating/updating one or more instances of a model.

If you're trying to reduce the number of network requests from the client to server, you could also look into query batching.

like image 163
Daniel Rearden Avatar answered Sep 23 '22 18:09

Daniel Rearden