Advertisement
Intermediate Node.js, GraphQL with Node.js

How do GraphQL Mutations differ from Queries, and how would you define one to create a new resource?

Short answer

Queries are for reading data and are expected to have no side effects, while Mutations are explicitly for operations that change server-side state (creating, updating, or deleting data) -- syntactically similar to queries but declared under the schema's Mutation type, with the…

Save Node.js mock interview
Advertisement
AModel answer
Queries are for reading data and are expected to have no side effects, while Mutations are explicitly for operations that change server-side state (creating, updating, or deleting data) -- syntactically similar to queries but declared under the schema's Mutation type, with the convention that mutations are executed sequentially (one at a time) when multiple are included in a single request, unlike queries which can be resolved in parallel.
const typeDefs = gql`
  type Mutation { createUser(name: String!, email: String!): User! }
`;

const resolvers = {
  Mutation: {
    createUser: async (_, { name, email }) => {
      return db.users.create({ name, email });
    },
  },
};

// Client sends: mutation { createUser(name: "Alice", email: "alice@example.com") { id name } }
Real-world example
A social media application defines a 'createPost' mutation that validates the input, saves the new post to the database, and returns the created post's fields the client requested, following GraphQL's convention of separating this state-changing operation clearly from the app's read-only query operations.
Likely follow-ups
  • Why does GraphQL execute multiple mutations in a single request sequentially rather than in parallel like queries?
  • How do you handle partial failure when a mutation succeeds in modifying data but a subsequent part of the resolver fails?
Related topics