Day 3 of 5
⏱ ~60 minutes
GraphQL in 5 Days — Day 3

Mutations: Writing Data

Define mutations, write mutation resolvers, and handle validation.

Mutations in the Schema

Schema additions
const typeDefs = `#graphql
  type Mutation {
    createUser(input: CreateUserInput!): User!
    updateUser(id: ID!, input: UpdateUserInput!): User!
    deleteUser(id: ID!): Boolean!
    createPost(input: CreatePostInput!): Post!
  }

  input CreateUserInput {
    name: String!
    email: String!
  }

  input UpdateUserInput {
    name: String
    email: String
  }

  input CreatePostInput {
    title: String!
    body: String
    authorId: ID!
  }
`
Mutation Resolvers
const resolvers = {
  Mutation: {
    createUser: (_, { input }) => {
      const user = { id: String(users.length + 1), ...input };
      users.push(user);
      return user;
    },
    updateUser: (_, { id, input }) => {
      const user = users.find(u => u.id === id);
      if (!user) throw new Error('User not found');
      Object.assign(user, input);
      return user;
    },
    deleteUser: (_, { id }) => {
      const idx = users.findIndex(u => u.id === id);
      if (idx === -1) return false;
      users.splice(idx, 1);
      return true;
    },
  }
};
Running a mutation
mutation CreateUser {
  createUser(input: {
    name: "Carol"
    email: "[email protected]"
  }) {
    id
    name
    email
  }
}
📝 Day 3 Exercise
Add Mutations to Your API
  1. A
  2. d
  3. d
  4. c
  5. r
  6. e
  7. a
  8. t
  9. e
  10. U
  11. s
  12. e
  13. r
  14. ,
  15. u
  16. p
  17. d
  18. a
  19. t
  20. e
  21. U
  22. s
  23. e
  24. r
  25. ,
  26. a
  27. n
  28. d
  29. d
  30. e
  31. l
  32. e
  33. t
  34. e
  35. U
  36. s
  37. e
  38. r
  39. m
  40. u
  41. t
  42. a
  43. t
  44. i
  45. o
  46. n
  47. s
  48. .
  49. U
  50. s
  51. e
  52. i
  53. n
  54. p
  55. u
  56. t
  57. t
  58. y
  59. p
  60. e
  61. s
  62. .
  63. T
  64. e
  65. s
  66. t
  67. a
  68. l
  69. l
  70. t
  71. h
  72. r
  73. e
  74. e
  75. i
  76. n
  77. G
  78. r
  79. a
  80. p
  81. h
  82. i
  83. Q
  84. L
  85. .
  86. A
  87. d
  88. d
  89. b
  90. a
  91. s
  92. i
  93. c
  94. v
  95. a
  96. l
  97. i
  98. d
  99. a
  100. t
  101. i
  102. o
  103. n
  104. (
  105. t
  106. h
  107. r
  108. o
  109. w
  110. a
  111. n
  112. e
  113. r
  114. r
  115. o
  116. r
  117. i
  118. f
  119. e
  120. m
  121. a
  122. i
  123. l
  124. a
  125. l
  126. r
  127. e
  128. a
  129. d
  130. y
  131. e
  132. x
  133. i
  134. s
  135. t
  136. s
  137. )
  138. .

Day 3 Summary

  • Mutations modify data. Same GraphQL format as queries but use the mutation keyword.
  • Input types group mutation arguments: input: CreateUserInput!.
  • Throw errors in resolvers for validation failures — GraphQL catches and returns them in the errors array.
  • The mutation response should include the created/updated object so the client can update its cache.
Finished this lesson?