How can i run one mutation multiple times with dif

2020-04-14 16:17发布

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?

2条回答
不美不萌又怎样
2楼-- · 2020-04-14 16:34

It's not possible so easily.

Because the mutation has one consistent name and graphql will not allow to have the same operation multiple times in one query. So for this to work Apollo would have to map the mutations into aliases and then even map the variables data into some unknown iterable form, which i highly doubt it does.

查看更多
手持菜刀,她持情操
3楼-- · 2020-04-14 16:40

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.

查看更多
登录 后发表回答