问题描述
我有一个突变:
const createSomethingMutation = gql` mutation($data: SomethingCreateInput!) { createSomething(data: $data) { something { id name } } } `;
如何在一个请求中创建许多Something?我是否需要在我的GraphQl Server上创建一个新的突变:
mutation { addManySomethings(data: [SomethingCreateInput]): [Something] }
还是有一种方法可以多次使用Apollo客户端的现有createSomethingMutation在一个请求中使用不同的参数?
推荐答案
您实际上可以使用别名进行此操作,并为每个别名分开变量:
const createSomethingMutation = gql` mutation($dataA: SomethingCreateInput!) { createA: createSomething(data: $dataA) { something { id name } } createB: createSomething(data: $dataB) { something { id name } } } `;
您可以看到更多的别名示例 spec .
然后,您只需要提供两个属性的变量对象 - dataA和dataB.但是,如果您需要动态的突变数量,事情可能会变得非常凌乱.通常,在这种情况下,仅仅暴露单个突变以处理/更新模型的一个或多个实例,可能会更容易(并且更有效).
如果您正在尝试减少客户端的网络请求数量到服务器,则还可以查看查询批处理.
其他推荐答案
这是不可能的.
因为该突变具有一个一致的名称,并且GraphQl将不允许在一个查询中多次具有相同的操作.因此,为此,Apollo必须将突变映射到别名中,然后将variables数据映射到某种未知的迭代形式中,我非常怀疑它确实如此.
问题描述
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?
推荐答案
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.
其他推荐答案
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.