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

人盡茶涼 提交于 2020-03-16 09:00:23

问题


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?


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/50889548/how-can-i-run-one-mutation-multiple-times-with-different-arguments-in-one-reques

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!