2

Is it meanwhile possible to use the result of a GraphQL mutation as a parameter for another mutation?

I would like to create a user and his address together in one call.

First I write the address and then take the address id for the creation of the user. Filling the necessary data via the inputs works perfectly

Is this possible without triggering a new mutation from the client?

const createUser = gql`
  mutation createUser(
    $user: createUserInput!
    $address: createAddressInput!
  ) {
    createAddress(input: $address) {
      address {
        id       
      }
    }
    createUser(input: $user ) {
      user {
        id
        username
      }
    }
  }
`
jasie
  • 2,192
  • 10
  • 39
  • 54
MarkusH
  • 21
  • 2
  • You would need to add a third mutation that does both operations together. Calling two mutations, one after another implies two calls from the client. – Alejandro Dec 13 '21 at 14:56
  • you are right about the two calls, but is it possible to get the address id directly in the createUser call? – MarkusH Dec 13 '21 at 15:17
  • Not directly. Since we're talking of two calls they're are independent. The client must supply the parameter, even if it comes as the output of a previous mutation. If keeping the same schema, it's client responsability. If you add another, "two-in-one" mutation, then the server can know to forward the data internally. – Alejandro Dec 13 '21 at 15:27

1 Answers1

1

No, this is not possible. You either have to make two sequential requests from the client, or adapt your server implementation. I recommend the latter.

You should change your schema so that the CreateUserInput type to not only accepts an addressId: ID but alternatively can accept a newAddress: CreateAddressInput object, which it will then use to create a new address before creating a new user.

Bergi
  • 630,263
  • 148
  • 957
  • 1,375