Mutations — Creating & Updating Data

◕ GraphQLLesson 4Beginner

In GraphQL, mutations are used for all write operations — creating, updating, and deleting data. Unlike REST which uses different HTTP methods, GraphQL uses mutations for all data modifications through a single POST /graphql endpoint.

1 Writing Mutations
GraphQL — Mutation Examples
# Create a new user
mutation CreateUser {
  createUser(input: {
    name:     "Balaji Nayak"
    email:    "balaji@example.com"
    password: "SecurePass123!"
    role:     USER
  }) {
    id
    name
    email
    createdAt
  }
}

# Update a post
mutation UpdatePost {
  updatePost(id: "post-42", input: {
    title: "Updated Title"
    body:  "New content here..."
  }) {
    id
    title
    updatedAt
    author { name }
  }
}

# Delete — return boolean or deleted ID
mutation DeleteComment {
  deleteComment(id: "comment-7") {
    success
    message
  }
}
2 Multiple Mutations in One Request
GraphQL — Sequential Mutations
# Multiple mutations run SEQUENTIALLY (in order), unlike queries
mutation BatchCreate {
  createCategory: createPost(input: { title: "Category Post", body: "..." }) {
    id title
  }
  pinPost: updatePost(id: "10", input: { isPinned: true }) {
    id isPinned
  }
}

# Response includes both results
{
  "data": {
    "createCategory": { "id": "99", "title": "Category Post" },
    "pinPost": { "id": "10", "isPinned": true }
  }
}
3 Mutation Return Types Best Practice
GraphQL SDL — Mutation Payload Pattern
# Return a dedicated payload type for rich error info
type CreateUserPayload {
  user:   User
  errors: [UserError!]
}

type UserError {
  field:   String!
  message: String!
}

type Mutation {
  createUser(input: CreateUserInput!): CreateUserPayload!
}

# Client query:
mutation {
  createUser(input: { name: "", email: "bad" }) {
    user { id name }
    errors {
      field
      message
    }
  }
}
4 Code Challenge
Challenge: Write mutations for a shopping cart: addToCart(productId, quantity), updateCartItem(itemId, quantity), and checkout(cartId, paymentMethod). Use payload types with both a success result and an errors array.