Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
798 views
in Technique[技术] by (71.8m points)

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

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...