如何在一个请求中使用不同的参数多次运行一个突变? [英] How can i run one mutation multiple times with different arguments in one request?
问题描述
我有一个突变:
const createSomethingMutation = gql`
mutation($data: SomethingCreateInput!) {
createSomething(data: $data) {
something {
id
name
}
}
}
`;
如何在一个请求中创建多个Something
?我是否需要在我的GraphQL服务器上创建一个新的Mutation,像这样:
How do I create many Something
s in one request? Do I need to create a new Mutation on my GraphQL server like this:
mutation {
addManySomethings(data: [SomethingCreateInput]): [Something]
}
或者是否有一种方法可以在一个请求中多次使用具有不同参数的Apollo Client现有的createSomethingMutation
?
Or is there a way to use the one existing createSomethingMutation
from Apollo Client multiple times with different arguments in one request?
推荐答案
实际上,您可以使用别名来做到这一点,并为每个别名分别设置变量:
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.
然后,您只需要提供一个具有两个属性的变量对象-dataA
和dataB
.但是,如果您需要动态变化的数量,事情就会变得很混乱.通常,在这种情况下,只暴露一个突变来处理创建/更新一个或多个模型实例可能会更容易(更有效).
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.
这篇关于如何在一个请求中使用不同的参数多次运行一个突变?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!