Skip to content
Tutorials Center
My learning

Topics

Lesson 32 of 37 ยท Projects

Project: A Todo API with Mutations

Build a todo API in GraphQL: input objects, mutation payload types, validation errors as data and an optimistic client flow, all as runnable stand-ins.

Reading data is the easy half of an API. In this project you design the write side: a todo list with queries and mutations, inputs that are validated, payload types that return the changed object, and a client that updates its screen before the server answers.

As always, no real GraphQL server runs here. The schema is real SDL in read-only blocks. The server logic is runnable Node code that follows the same shape as resolvers behind a real server; operations are passed as plain JavaScript objects ({ field, args }) instead of query text, because parsing was covered in earlier lessons and would only add noise. You should be comfortable with Mutations and Subscriptions and the ideas in Modeling Errors.

The schema

Design rules for writes

One input object createTodo(input: CreateTodoInput!)
Specific mutations toggleTodo, not updateTodo with flags.
Payload types Return the todo and any user errors.

Expected failures like a blank title are data, not exceptions.

1 / 2
GRAPHQL
type Todo {
  id: ID!
  title: String!
  done: Boolean!
  createdAt: String!
}

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

input CreateTodoInput {
  title: String!
}

type CreateTodoPayload {
  todo: Todo
  userErrors: [UserError!]!
}

type ToggleTodoPayload {
  todo: Todo
  userErrors: [UserError!]!
}

type DeleteTodoPayload {
  deletedId: ID
  userErrors: [UserError!]!
}

type Query {
  todos(done: Boolean): [Todo!]!
  todo(id: ID!): Todo
}

type Mutation {
  createTodo(input: CreateTodoInput!): CreateTodoPayload!
  toggleTodo(id: ID!): ToggleTodoPayload!
  deleteTodo(id: ID!): DeleteTodoPayload!
}

Three decisions are worth noting. Each mutation has its own payload type so you can add fields later without breaking anyone. The payload's todo is nullable, because on failure there is nothing to return. And userErrors always exists ([UserError!]!), so clients can check userErrors.length without a null check. A blank title is something users do, so it comes back as data. A crashed database would still be a top-level error.

The server logic

The in-memory "database" is a Map. Each mutation resolver validates, changes data and returns a payload. The serve function runs the root fields of a request serially (as the specification requires for mutations) and builds a data object keyed by response name.

Node.js Todo server logic: queries, mutations and user errors

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Check the responses against the design. The blank title gave todo: null plus an entry in userErrors with a code the UI can branch on, and the request still counts as a success at the GraphQL level. The two mutations in the first request ran in order, so ids are 1 and 2. In "toggle one, miss one" one field succeeded while the other returned a NOT_FOUND error, because each root field has its own payload.

Real servers add what this stand-in leaves out: they parse and validate the query text, check that input has the right shape (a missing title is rejected by validation before your resolver runs), and add the __typename field. Your resolver still owns the business rules, such as the length limit.

The optimistic client flow

Waiting for the server before updating the screen makes an app feel slow. An optimistic update shows the expected result immediately, using a temporary id, then reconciles when the real response arrives:

  1. Add the todo to the local list with a temporary id.
  2. Send the mutation.
  3. On success, replace the temporary item with the server's todo (real id).
  4. On userErrors or a network error, remove the temporary item and show the message.

Real client libraries (Apollo Client, urql, Relay) provide hooks for exactly this (an optimisticResponse, for example); those are read-only for us. The stand-in below shows the underlying logic with a fake server that answers after a short delay and rejects long titles.

Node.js Optimistic create with rollback

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Notice the pending flag. Without it, the UI cannot tell a confirmed item from a guess (you might show it greyed out). Also notice that rollback uses the temporary id to find the item again, never an array position captured earlier, because other updates may have changed the list meanwhile.

Extend the project

  • Add renameTodo(id, input: RenameTodoInput!) reusing the title validation.
  • Add a todos(filter: TodoFilter, first: Int) query with pagination.
  • Add a todoChanged subscription and publish an event from every mutation.
  • Require a logged-in user and store ownerId on each todo (Authentication and Authorization).

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why does createTodo return a payload type instead of just Todo?

    A payload type leaves room for user errors and future fields. Returning the bare object would make both changes harder.
  2. 2. A user submits a blank title. How should the API report it in this design?

    A blank title is an expected, user-fixable problem, so it is modeled as data the UI can branch on.
  3. 3. Two mutation fields appear in one request. In which order do they run?

    The specification requires mutation root fields to run one after another.
  4. 4. In an optimistic update, how do you remove a rejected item reliably?

    Other updates may change positions while the request is in flight, so identify the item by its temporary id.

Summary

  • Give each mutation one input object and its own payload type.
  • Return the changed object plus userErrors, so expected failures are data.
  • Keep business validation in resolvers or the layer below them.
  • Mutation root fields run serially; each one can succeed or fail on its own.
  • Optimistic UIs add a pending item, then reconcile or roll back using a temporary id.

Next: Project: A Blog with DataLoader and Pagination.