如何在一个请求中使用不同的参数多次运行一个突变? [英] How can i run one mutation multiple times with different arguments in one request?

查看:39
本文介绍了如何在一个请求中使用不同的参数多次运行一个突变?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个突变:

const createSomethingMutation = gql`突变($数据:SomethingCreateInput!){创建东西(数据:$数据){某物 {ID姓名}}}`;

如何在一个请求中创建多个 Something ?我是否需要像这样在我的 GraphQL 服务器上创建一个新的 Mutation:

变异{addManySomethings(data: [SomethingCreateInput]): [Something]}

或者有没有办法在一个请求中多次使用来自 Apollo Client 的现有 createSomethingMutation 和不同的参数?

解决方案

实际上,您可以使用别名来做到这一点,并为每个别名单独使用变量:

const createSomethingMutation = gql`突变($dataA:SomethingCreateInput!){createA: createSomething(data: $dataA) {某物 {ID姓名}}createB: createSomething(data: $dataB) {某物 {ID姓名}}}`;

您可以在规范中查看更多别名示例.>

然后你只需要提供一个带有两个属性的变量对象——dataAdataB.但是,如果您需要动态的突变数量,事情会变得非常混乱.通常,在这种情况下,仅公开一个突变来处理创建/更新模型的一个或多个实例可能更容易(也更有效).

如果您想减少从客户端到服务器的网络请求数量,您还可以查看 查询批处理.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆