0

Say I have a book-sharing app, and given say a user with a collection of favorite books, when adding a favorite book is the most common best practice that we just use editUser mutation and update their collection of favorites in the user object itself, or use a named addFavorite mutation that just sends along the book to add?

type Book {
  title: String
  author: Author
}

type User {
  name: String
  address: Address
  favorites: [Book]
}

My opinion is that it's clearer and better to have a named mutation for addFavorite since it's the key use case and it's clearer to have mutations that add relationships rather than having it implied through the update of another object.

mutation AddFavorite($userId: ID!, $book: BookInput!) {
  addFavorite(userId: $userId, book: $book)
}

vs

mutation EditUser($userId: ID!, $input: UserInput!) {
  editUser(userId: $userId, input: $input) {
}

input UserInput {
  name: String
  address: Address
  addFavorite: [Book!]
}
MonkeyBonkey
  • 46,433
  • 78
  • 254
  • 460
  • I think Graphql was invented to help us fetch/post exact data we want. Having this principal in mind I think `AddFavorite` is more specific and its server implementation is specific too. Though even second option would be ideal too. So its just the matter of your own preference. For me I would go with first option – Nux May 03 '23 at 08:14
  • Assuming the user who is running the mutation is the user you want to add the favorite to then you shouldn't even pass the user's ID to the mutation - the server knows who the current user is. Agree with @Nux that the first style is preferred since it doesn't make assumptions about how the data is stored - ex: maybe at some point favorites become their own collection but the front end won't need to care. – Michel Floyd May 03 '23 at 16:17

0 Answers0