简体   繁体   中英

graphql: single mutation or one mutation per type

I have a GraphQL schema like this:

type User {
 id: ID
 name: String
 email: String
 addresses: [UserAddress] 
}

type UserAddress {
 id: ID
 city: String
 country: String
}

I always have doubts about how to make the best design for mutations. (I'm using apollo + prisma)

These are my options:

1) One single mutation

I need to create this mutation and input type:

input userAddressInput {
 id: ID
 city: String
 country: String
}

mutation updateUser (
 id: ID
 name: String
 email: String
 addresses: UserAddressInput
): User    

Then I execute mutations like this:

mutation updateUserData($id: ID, $name: String, $email: String) {
  updateUser(id: $id, name: $name, email: $email) {      
    id
    name
    email      
  }
}

mutation updateUserAddress($id: ID, $userAddress: UserAddressInput) {
  updateUser(id: $id, userAddress: $userAddress) {      
    id
    addresses {
     id
     city
     country  
    }            
  }
}

And resolvers like this:

Mutation: {
 updateUser: (_, args) => {

  if (args.name || args.email) {
     // update model User by args.userData.id
  }

  if (args.userAddress) {
     // update model UserAddress by args.userAddress.id
  }

 }
}

2) One mutation per type

I don't need to create any input type but I need two mutations:

mutation updateUser (
 id: ID
 name: String
 email: String     
): User  

mutation updateUserAddress (
 id: ID
 city: String
 country: String     
): UserAddress  

Then mutations like this:

mutation updateUser($id: ID, $name: String, $email: String) {
  updateUser(id: $id, name: $name, email: $email) {      
    id
    name
    email      
  }
}

mutation updateUserAddress($id: ID, $city: String, $country: String) {
  updateUserAddress(id: $id, city: $city, country: $country) {      
    id
    city
    country      
  }
}

And resolvers like this:

Mutation: {
 updateUserAddress: (_, args) => {
  // update model UserAddress by args.id
 }
 updateUser: (_, args) => {  
  // update model User by args.id
 } 
}

What is the best way to deal with such cases?

It depends what your use case is.

Does your GUI allow for update of a user's addresses without also updating the user info? If so you will likely need a separate mutation for updating only the addresses.

If you are allowing user and addresses to be edited and saved as one operation then individual mutations would require you to send multiple HTTP requests (one per mutation).

Do you need to update the user and addresses as an atomic transaction (ie all or nothing)? If so then you should use a single mutation.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM