Designing mutation inputs and payloads

Intermediate · 9 min

One input object and one payload type per mutation, expected failures as userErrors, and the difference between an omitted field and an explicit null.

Before thisMutationsInput typesNon-null and lists

TomDoesTech · 9 min

Designing mutation inputs and payloads

The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.

Taught by TomDoesTechReport a problem with this video
Not started
Set this lesson's status

What you'll learn

  • Give each mutation a single `input` argument of an input type, so adding an optional field later is not a breaking change.
  • Return a dedicated payload type such as `CreatePostPayload` rather than a bare `Post`; the payload is the place to add the changed object, errors and anything else the client needs.
  • Report expected failures like validation or not-found as data, for example a `userErrors` list, and keep the top-level `errors` array for faults and invalid operations.
  • In an update input, a missing key and an explicit `null` are different; check for the key with `in` before treating null as 'clear this field'.
  • Make the changed object nullable on the payload, because on failure there is nothing to return.

The problem with a bare mutation

Start with the version from the last lesson: createPost(authorId: ID!, title: String!): Post!. Two things go wrong as the app grows.

First, arguments. You add body, then tags, then publishAt. Every call site now has a long list, and a mutation with eight arguments is hard to read and hard to extend. Second, the return type. Post! has no room for “this failed because the title was blank.” The only way to say so is to throw, which turns an everyday outcome into an error.

Both are solved by treating each mutation as a tiny request and response pair.

One input, one payload

input CreatePostInput {
  authorId: ID!
  title: String!
  body: String = ""
}

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

type CreatePostPayload {
  post: Post
  userErrors: [UserError!]!
}

type Mutation {
  createPost(input: CreatePostInput!): CreatePostPayload!
}

The convention is one argument named input and one return type named <Mutation>Payload. Adding tags: [String!] to the input later is safe, because input fields may be optional. Adding publishedAt to the payload is safe too, because clients only receive what they select. The signature never has to change.

The client sends one variable:

mutation Create($input: CreatePostInput!) {
  createPost(input: $input) {
    post { id title author { name } }
    userErrors { field message }
  }
}

I ran this against Yoga 6.1.0 and SQLite. A valid call returns:

{ "data": { "createPost": {
  "post": { "id": "11", "title": "Hello", "author": { "name": "Grace" } },
  "userErrors": [] } } }

A call with a blank title and an author id that does not exist returns:

{ "data": { "createPost": {
  "post": null,
  "userErrors": [
    { "field": ["input", "title"], "message": "Title cannot be blank" },
    { "field": ["input", "authorId"], "message": "Author not found" } ] } } }

HTTP status is 200, and there is no top-level errors array.

Which failures are data

Two kinds of failure exist, and they deserve different homes.

Expected outcomes are part of the contract: blank title, duplicate email, post not found. The client wants to show them beside a form field. Return them in the payload, as above. The field path points at the input that caused the problem.

Unexpected faults are not the client’s to handle: the database is down, a bug threw. Those belong in the top-level errors array. Errors and partial responses covers how they flow.

Missing a required field is a third case, handled before your resolver runs. Sending { "title": "x" } without authorId fails validation and the server answers with an errors entry saying the input is missing required field authorId. Your resolver never executes. A type system rejecting the shape is the cheapest validation you will ever write; use String! for what is truly required and keep business rules in the resolver.

userErrors is one convention among several. A union return type such as CreatePostResult = CreatePostSuccess | ValidationError gives clients typed errors via inline fragments. It costs more schema. Start with userErrors and move to unions when different failures carry different data. The unions lesson has the mechanics.

Updates: omitted versus null

A partial update has a trap. Consider:

input UpdatePostInput {
  id: ID!
  title: String
  body: String
}

A client that wants to change only the title sends { id: "1", title: "New" }. Another that wants to erase the body sends { id: "1", body: null }. Do they look the same to the resolver? Checked with graphql-js 17.1.0:

{ id: "1", title: "T" }              -> 'body' in input === false
{ id: "1", title: "T", body: null }  -> 'body' in input === true, input.body === null

They differ, but only if you ask the right question. input.body ?? current.body collapses both into “leave unchanged”, so the client can never clear a field. Test with in:

const body = 'body' in input ? input.body : current.body;

If a field must never be cleared, reject an explicit null in the resolver with a userErrors entry, and say so in the field’s description. Marking it String! would make every update send it, which defeats a partial update.

Return what changed, even for deletes

Return the affected object so the client can update its view. For a delete the object is gone, so return what the client needs to remove it:

type DeletePostPayload {
  deletedPostId: ID
  userErrors: [UserError!]!
}

That mirrors the first example: the id is nullable because deleting a missing post fails with a userErrors entry and no id.

What the video covers

TomDoesTech’s “Stop Making These 5 GraphQL Mistakes” lists its mistakes in the description: using GraphQL as a REST or RPC API, not using an input type for mutations, not returning the modified object from mutations, not using field resolvers, and having several queries for the same node type. Mistakes two and three are this lesson; the others are useful, but the video does not cover payload types with error lists or the omitted-versus-null case, so the sections above do that work. The video is from 2023 and its code may not match this lesson’s server, though the schema advice is independent of it.

Where this fits

You can now shape a mutation that is easy to extend and reports failure as data. The next step moves past request and response: telling clients about events as they happen. Next: subscriptions.

Check yourself

  1. 01Why is `createPost(input: CreatePostInput!)` easier to evolve than `createPost(title: String!, body: String)`?

    A new optional field on the input type is a non-breaking change and old clients keep working. A growing argument list also gets hard to read, and variables can carry a single `$input` object.

  2. 02Where does a 'title cannot be blank' failure belong in the response?

    In the payload as data, such as `userErrors`, since it is an expected outcome the client should display next to a field. The top-level `errors` array is for unexpected faults and malformed operations.

  3. 03How can a resolver tell `{ body: null }` from an input that left `body` out?

    Check `'body' in input`. The key is present with a null value in the first case and absent in the second, which lets you clear a field only when the client asks to.

  4. 04Why is `post` nullable on `CreatePostPayload` even though a successful call always returns one?

    A failed call has no post to return. A non-null `post` would force the server to invent one or null out the whole payload.

Go deeper

Notes

Private to you

Esc
↑↓ navigate↵ open? shortcuts

Keyboard shortcuts

Press Esc to close

Anywhere

⌘K
Search and commands
/
Search
?
This sheet
Esc
Close

Reading a lesson

J
Next lesson
K
Previous lesson
B
Bookmark